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], ]跟前面那个没什么区别,你要顺序添加了做一个reverse也行。
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if ( !root )
return vector<vector<int> >();
deque<vector<int> > ans;
vector<int> level;
queue<TreeNode* > Q;
Q.push(root);
int lsum=1;
while(lsum)
{
level.clear();
int next=0;
while(lsum--)
{
TreeNode* t=Q.front();
Q.pop();
level.push_back(t->val);
if ( t->left )
{
Q.push(t->left);
next++;
}
if ( t->right)
{
Q.push(t->right);
next++;
}
}
ans.push_front(level);
lsum=next;
}
return vector<vector<int> >(ans.begin(),ans.end());
}
};