Binary Tree Level Order Traversal II
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], ]
confused what "{1,#,2,3}" means > read more on how binary tree is serialized on OJ.
算法思想:
从前往后,从右向左处理完,然后逆序输出
/**
* 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
> levelOrderBottom(TreeNode *root){
vector
> result; if(!root)return result; list
> r; list
t; int curLev=1; int nextLev=0; queue
que; que.push(root); while(!que.empty()){ TreeNode *cur=que.front(); que.pop(); t.push_front(cur->val); if(cur->right){ nextLev++; que.push(cur->right); } if(cur->left){ nextLev++; que.push(cur->left); } if(--curLev==0){ r.push_front(t); t.clear(); curLev=nextLev; nextLev=0; } } for(auto &v:r){ vector
k; for(int i:v){ k.push_back(i); } result.push_back(k); } return result; } };