Binary Tree Postorder Traversal
2014-03-25 06:43
351 查看
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> res;
stack<TreeNode* > sta;
TreeNode* cur = root;
TreeNode* pre = 0;
while (0 != cur || !sta.empty())
{
if (0 != cur)
{
sta.push(cur);
cur = cur->left;
}
else if (!sta.empty())
{
TreeNode* tmp = sta.top();
if (0 == tmp->right || tmp->right == pre)
{
res.push_back(tmp->val);
sta.pop();
pre = tmp;
}
else
cur = tmp->right;
}
}
return res;
}
};
For example:
Given binary tree
{1,#,2,3},
1 \ 2 / 3
return
[3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> res;
stack<TreeNode* > sta;
TreeNode* cur = root;
TreeNode* pre = 0;
while (0 != cur || !sta.empty())
{
if (0 != cur)
{
sta.push(cur);
cur = cur->left;
}
else if (!sta.empty())
{
TreeNode* tmp = sta.top();
if (0 == tmp->right || tmp->right == pre)
{
res.push_back(tmp->val);
sta.pop();
pre = tmp;
}
else
cur = tmp->right;
}
}
return res;
}
};
相关文章推荐
- windows服务器记录3389远程桌面IP策略
- Win7、win2008中让IIS7支持asp的方法
- Permutation Sequence -- LeetCode
- 释构函数的调用顺序
- [SQL]reName存储过程
- [SQL]patindex的用法
- 1078. Hashing (25)
- [SQL]不知道1
- [SQL]当输入表达式得数为一个有效的整数、浮点数、money 或 decimal 类型,那么 ISNUMERIC 返回 1;否则返回 0
- [SQL] 要查询9 月份的数据中的任意时间段,可能是一个月的,也可能是1日到15日的
- [大牛翻译系列]Hadoop(22)附录D.2 复制连接框架
- 使用拷贝构造函数和赋值运算符的区别
- [SQL]详解CUBE和ROLLUP区别<使用rollup或cube通过交叉列可产生高级汇总结果集>
- list操作
- TDD中的单元测试写多少才够?
- Android 通过httpclient请求web服务器,并解决用户登录session保持
- [SQL] cast 与 convert 都在什么情况下使用
- [SQL]不知道
- 独立第二天
- debian编译内核时err: line 65 dpkg-gencontrol command not found