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] ]思路:宽度优先搜索,使用队列,与Binary Tree Level Order Traversal类似,最后将结果反转即可
代码:
/**
* Definition for binary tree
* 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> > res;
if(root==NULL) return res;
vector<int> temp;
queue<TreeNode*> wfs;
wfs.push(root);
int level=0;
int count=1;
TreeNode *tmp;
while(!wfs.empty()){
temp.clear();
level=0;
for(int i=0;i<count;i++){
tmp=wfs.front();
wfs.pop();
temp.push_back(tmp->val);
if(tmp->left!=NULL){
wfs.push(tmp->left);
level++;
}
if(tmp->right!=NULL){
wfs.push(tmp->right);
level++;
}
}
count=level;
res.push_back(temp);
}
reverse(res.begin(),res.end());
return res;
}
};