题目描述
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
pre(root,0,res);
vector<vector<int>> res2;
for(int i=res.size()-1;i>=0;i--){
res2.push_back(res[i]);
}
return res2;
}
void pre(TreeNode *root, int depth, vector<vector<int>> &res){
if(!root) return ;
if(depth >= res.size())
res.push_back(vector<int> {});
res[depth].push_back(root->val);
pre(root->left,depth+1,res);
pre(root->right,depth+1,res);
}
};