LintCode 二叉树的层次遍历 II

时间:2022-03-31 20:08:11

中等 二叉树的层次遍历
II
查看执行结果

42%
通过

给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)

您在真实的面试中是否遇到过这个题?

Yes
例子

给出一棵二叉树 {3,9,20,#,#,15,7},

    3
/ \
9 20
/ \
15 7

依照从下往上的层次遍历为:

[
[15,7],
[9,20],
[3] ]

asd

/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/ class Solution {
/**
* @param root : The root of binary tree.
* @return : buttom-up level order a list of lists of integer
*/
public:
vector<vector<int>> levelOrderBottom(TreeNode *root) {
vector<vector<int>> res;
if(root == nullptr) {
return res;
}
vector<int> temp;
queue<TreeNode*> q;
stack<vector<int>> s;
q.push(root);
int i = 1;// points every level
int j = 0;// lost point every level
while(!q.empty()) {
TreeNode *p = q.front();
q.pop();
if (p==nullptr) {
++j;
}
else {
temp.push_back(p->val);
q.push(p->left);
q.push(p->right);
}
if (i == (temp.size() + j) && temp.size()!=0) {
s.push(temp);
temp.clear();
i*=2;
j*=2;
}
}
while(!s.empty()) {
res.push_back(s.top());
s.pop();
}
return res;
}
};