题目链接:https://leetcode-cn.com/problems/binary-tree-right-side-view/
题目描述:
1.二叉树的右视图
思路:二叉树层序遍历的时候,判断是否遍历到单层的最后面的元素,如果是,就放进result数组中。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
queue<TreeNode *> que;
if(root != nullptr)
que.push(root);
while(!que.empty())
{
int currentLevel = que.size();
TreeNode *node;
for(int i = 0; i < currentLevel; i++)
{
node = que.front();
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
result.push_back(node->val); //本层的最后一个节点
}
return result;
}
};
2.二叉树的层平均值
题目链接:https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/
题目描述:给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
题解:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> result;
queue<TreeNode *> que;
if(root != NULL)
que.push(root);
while(!que.empty())
{
int currentLevel = que.size();
double sum = 0;
for(int i = 0; i < currentLevel; i++)
{
TreeNode *node = que.front();
que.pop();
sum += node->val;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
result.push_back(sum / currentLevel);
}
return result;
}
};
3.N叉树的层序遍历
题目链接:https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/
题目描述:给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。
解题:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> result;
queue<Node *> que;
if(root != NULL)
que.push(root);
while(!que.empty())
{
vector<int> vec;
int currentLevel = que.size();
for(int i = 0; i < currentLevel; i++)
{
Node *p = que.front();
que.pop();
vec.push_back(p->val);
for(int i = 0; i < p->children.size(); i++) //节点的孩子入队
{
if(p->children[i])
que.push(p->children[i]);
}
}
result.push_back(vec);
}
return result;
}
};