逆序输出:
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
递归进行层次遍历,每层相当于一个vector<int>,由于与层数有关故引入层数参数:
class Solution {
private:
vector<vector<int>>res;
public:
void levelOrder(struct TreeNode* root,int level){
if(root==NULL)return ;
if(level==res.size()){
vector<int> v;
res.push_back(v);
}
res[level].push_back(root->val);
levelOrder(root->left,level+1);
levelOrder(root->right,level+1);
}//确定是level层而不是level-1层
vector<vector<int>> levelOrderBottom(struct TreeNode* root) {
levelOrder(root,0);
return vector<vector<int>>(res.rbegin(),res.rend());
}
};
顺序输出:
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
class Solution {
private:
vector<vector<int>>res;
public:
void levelOrder(struct TreeNode* root,int level){
if(root==NULL)return ;
if(level==res.size()){
vector<int> v;
res.push_back(v);
}
res[level].push_back(root->val);
levelOrder(root->left,level+1);
levelOrder(root->right,level+1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
levelOrder(root,0);
return res;
}
};