给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [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) {
queue<TreeNode*> temp;
vector<vector<int>> result;
vector<int> s;
temp.push(root);
int now = 0, last = 1;
while(!temp.empty()){
TreeNode *p = temp.front();
temp.pop();
if(p){
last--;
s.push_back(p->val); //存结果
//cout<<p->val<<endl;
if(p->left){
temp.push(p->left);
now++;
}
if(p->right){
temp.push(p->right);
now++;
}
}
if(!last){
vector<int> a;
a.assign(s.begin(), s.end());
result.push_back(a);
s.clear();
last=now;
now=0;
}
}
return result;
}
};
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
/**
* 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) {
queue<TreeNode*> temp;
vector<vector<int>> result;
vector<int> s;
temp.push(root);
int now = 0, last = 1;
while(!temp.empty()){
TreeNode *p = temp.front();
temp.pop();
if(p){
last--;
s.push_back(p->val); //存结果
//cout<<p->val<<endl;
if(p->left){
temp.push(p->left);
now++;
}
if(p->right){
temp.push(p->right);
now++;
}
}
if(!last){
vector<int> a;
a.assign(s.begin(), s.end());
result.push_back(a);
s.clear();
last=now;
now=0;
}
}
for(int layers = result.size(), i = 0; i < layers / 2; i++)
swap(result[i], result[layers-1-i]);
return result;
}
};