给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
样例
给出一棵二叉树 {3,9,20,#,#,15,7},
3
/
9 20
/
15 7
按照从下往上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
题目链接:http://www.lintcode.com/zh-cn/problem/binary-tree-level-order-traversal-ii/
跟上一道层次遍历的题目是相同的,为了倒过来访问,只需维护一个栈,把每层的结果亚茹栈中即可。
/**
* 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) {
// write your code here
vector<vector<int> > result;
if (!root) return result;
queue<TreeNode *> q;
stack<vector<int> > s;
q.push(root);
int len;
while (!q.empty()) {
vector<int> res;
len = q.size();
while (len--) {
TreeNode *temp = q.front();
res.push_back(temp->val);
q.pop();
if (temp->left) q.push(temp->left);
if (temp->right)q.push(temp->right);
}
s.push(res);
}
while (!s.empty()) {
result.push_back(s.top());
s.pop();
}
return result;
}
};