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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
if(!root) return {};
queue<TreeNode*> q;vector<vector<int>> v;
q.push(root);
while(!q.empty()){
vector<int> v1;
int m=q.size();
for(int i=0;i<m;++i){//这里不可以写成for(int i=0;i<q.size();++i),因为在for语句里q在不断push,所以每次循环q.size()都在变化
TreeNode *p=q.front();
q.pop();
v1.push_back(p->val);
if(p->left) q.push(p->left);
if(p->right) q.push(p->right);
}
v.push_back(v1);
}
// int n=v.size();
vector<vector<int>> v2;//(n,{});这里如果使用(n,{}),会报错,说是ambiguous(含糊的)
for(int i=v.size()-1;i>=0;--i){
v2.push_back(v[i]);
}
return v2;
}
};