題目描述
給定一個二叉樹,返回其節點值自底向上的層次遍歷。 (即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷)
例如:
給定二叉樹 [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);
}
};