107. 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,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
在102题基础上对输出结果进行反转操作,重新定义了一个vector,将102的结果倒序存入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>> lorder;
vector<vector<int>> lforder;
if(root == NULL)
{
return lorder;
}
queue<TreeNode*> q;
q.push(root);
vector<int> level_tmp2;
while(!q.empty())
{
level_tmp2.clear();
queue<TreeNode*> level_tmp1;
TreeNode* node = q.front();
int size = q.size(); for(int i = ; i < size; i++)
{
TreeNode* node = q.front();
q.pop();
if(node->left)
{
level_tmp1.push(node->left);
}
if(node->right)
{
level_tmp1.push(node->right);
}
level_tmp2.push_back(node->val);
}
while(!level_tmp1.empty())
{
q.push(level_tmp1.front());
level_tmp1.pop();
}
lorder.push_back(level_tmp2);
}
int n = lorder.size();
for(int i = n-; i >= ; i--)
{
lforder.push_back(lorder[i]);
}//reverse(lorder.begin(), lorder.end());
return lforder;
}
};