107. Binary Tree Level Order Traversal II
Easy
654120FavoriteShare
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理解了,这个就理解了。
下面是102详解链接:
https://blog.csdn.net/vivian0239/article/details/88555561
AC的代码:
/**
* 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>> y;
y.clear();
if(!root)return y;
queue<TreeNode*> que;
que.push(root);
while(que.size())
{
int num=que.size();
vector<int> x;
x.clear();
while(num>0)
{
TreeNode* t=que.front();
x.push_back(t->val);
que.pop();
if(t->left)que.push(t->left);
if(t->right)que.push(t->right);
num--;
}
y.push_back(x);
}
int s=y.size()/2;
int l=y.size()-1;
int t=0;
while(s>0)
{
vector<int> temp;
temp=y[t];
y[t]=y[l];
y[l]=temp;
s--;
t++;
l--;
}
return y;
}
};