给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
样例
例1:
输入:
{1,2,3}
输出:
[[2,3],[1]]
解释:
1
/ \
2 3
它将被序列化为 {1,2,3}
层次遍历
例2:
输入:
{3,9,20,#,#,15,7}
输出:
[[15,7],[9,20],[3]]
解释:
3
/ \
9 20
/ \
15 7
它将被序列化为 {3,9,20,#,#,15,7}
层次遍历
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A tree
* @return: buttom-up level order a list of lists of integer
*/
vector<vector<int>> levelOrderBottom(TreeNode * root) {
// write your code here
vector<vector<int>>res;
queue<TreeNode*>a;
queue<TreeNode*>b;
a.push(root);
if(root==NULL) return res;
vector<int> tmp={root->val};
res.push_back(tmp);
while(!a.empty()||!b.empty())
{
if(!a.empty())
{
tmp.clear();
while(!a.empty())
{
if(a.front()->left)
{
b.push(a.front()->left);
tmp.push_back(a.front()->left->val);
}
if(a.front()->right)
{
b.push(a.front()->right);
tmp.push_back(a.front()->right->val);
}
a.pop();
}
if(!tmp.empty())res.push_back(tmp);
}
if(!b.empty())
{
tmp.clear();
while(!b.empty())
{
if(b.front()->left)
{
a.push(b.front()->left);
tmp.push_back(b.front()->left->val);
}
if(b.front()->right)
{
a.push(b.front()->right);
tmp.push_back(b.front()->right->val);
}
b.pop();
}
if(!tmp.empty())res.push_back(tmp);
}
}
reverse(res.begin(),res.end());
return res;
}
};