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]
]
这道题就是遍历同一层的结点并且把同一级的结点PUSH进同一个vector,然后把每个同一级的vector push进一个总的vector,然后是用reverse函数把大vector里面的东西倒过来。
代码如下:
/**
* 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) {
vector<vector<int>>vv;
if(root==NULL)return vv;
queue<TreeNode*>q;
q.push(root);
int n=0;
while(!q.empty()){
vector<int>v;
for(int i=0,n=q.size();i<n;i++){
TreeNode * t=q.front();
q.pop();
if(t->left!=NULL)
q.push(t->left);
if(t->right!=NULL)
q.push(t->right);
v.push_back(t->val);
}
vv.push_back(v);
}
reverse(vv.begin(),vv.end());
return vv;
}
};
这里注意queue模板是用Push,而vector模板是用push_back