提示
LintCode中的相关算法题实现代码,可以在我的GitHub中下载。
题目需求
描述
给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
样例
给出一棵二叉树 {3,9,20,#,#,15,7}
,
3
/ \
9 20
/ \
15 7
按照从下往上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
解题思路
在原来的基础上增加一个栈即可,不了解原来解题思路的,可以看我的另外一篇博客二叉树的层次遍历。
实现代码
/**
* 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) {
stack<vector<int>> tmpResult;
vector<vector<int>> result;
if(root==NULL) return result;
queue<TreeNode*> nodes;
vector<int> tmp;
nodes.push(root);
int i=0;
while(nodes.size())
{
i=nodes.size();
int j=0;
while(j<i)
{
TreeNode* node=nodes.front();
tmp.push_back(node->val);
nodes.pop();
if(node->left)
nodes.push(node->left);
if(node->right)
nodes.push(node->right);
j++;
}
tmpResult.push(tmp);
tmp.clear();
}
while(tmpResult.size())
{
result.push_back(tmpResult.top());
tmpResult.pop();
}
return result;
}
};