描述
给定一个二叉树,返回该二叉树由底层到顶层的层序遍历,(从左向右,从叶子节点到根节点,一层一层的遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
该二叉树由底层到顶层层序遍历的结果是
[[15,7],[9,20],[3]]
示例1
输入:
{1,#,2}
返回值:
[[2],[1]]
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
queue<TreeNode*> q;
vector<vector<int>> vv;
if (root == NULL){
return vv;
}
int before = 0;
int current = 0;
if (root != NULL && q.empty()){
q.push(root);
current++;
}
while (!q.empty()){
vector<int>v;
before = current;
current = 0;
while(before--){
TreeNode *t = q.front();
if (t->left != NULL){
q.push(t->left);
current++;
}
if (t->right != NULL){
q.push(t->right);
current++;
}
v.push_back(t->val);
q.pop();
}
vv.push_back(v);
}
vector<vector<int>> res;
for (int i = vv.size()-1; i >= 0; --i){
res.push_back(vv[i]);
}
return res;
}
};