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] ]
/**
* 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<int> level;
vector<vector<int>> result;
vector<vector<int>> ans;
if(root==NULL)
return result;
queue<TreeNode*> q1,q2;
q1.push(root);
while(!q1.empty())
{
while(!q1.empty())
{
TreeNode* temp=q1.front();
q1.pop();
level.push_back(temp->val);
if(temp->left)
q2.push(temp->left);
if(temp->right)
q2.push(temp->right);
}
result.push_back(level);
level.clear();
swap(q1,q2);
}
while(!result.empty())
{
vector<int> tmp=result.back();
result.pop_back();
ans.push_back(tmp);
}
return ans;
}
};