1. 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
/**
* 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<vector<int>> levelOrder(TreeNode* root) {
if(!root) return {};
vector<vector<int>> res;
queue<TreeNode*> q{{root}};
while(!q.empty())
{
vector<int> temp;
for(int i = q.size();i > 0;i--)
{
TreeNode* t = q.front();
q.pop();
temp.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
res.push_back(temp);
}
return res;
}
};
2. 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
相比于1只需改变添加到结果数组的方式,添加到vector的头部即可。
/**
* 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<vector<int>> levelOrderBottom(TreeNode* root) {
if(!root) return {};
vector<vector<int>> res;
queue<TreeNode*> q{{root}};
while(!q.empty())
{
vector<int> temp;
for(int i = q.size();i > 0;i--)
{
TreeNode* t = q.front();q.pop();
temp.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
res.insert(res.begin(),temp);
}
return res;
}
};
3.
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
示例 1:
输入:
3
/ \
9 20
/ \
15 7
输出: [3, 14.5, 11]
解释:
第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
方法和1,2一样
/**
* 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) {
if(!root) return{};
vector<double> res;
queue<TreeNode*> q{{root}};
while(!q.empty())
{
double sum = 0,count = 0;
for(int i = q.size();i > 0;i--)
{
TreeNode* t = q.front();q.pop();
sum += t->val; count++;
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
res.push_back(sum / count);
}
return res;
}
};