binary-tree-postorder-traversal(后序遍历二叉树)
来源:互联网 发布:做淘宝客服工资多少 编辑:程序博客网 时间:2024/06/06 21:38
题目描述
Given a binary tree, return the postorder traversal of its nodes' values.
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?
非递归实现:
语言:C++ 运行时间: <1 ms 占用内存:8568K 状态:答案正确
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 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
> v;
stack<TreeNode*> s;
map<TreeNode*,
int
>mp;
//构造 节点指针,访问flag 的map
while
(root != NULL || !s.empty()){
while
(root != NULL){
s.push(root);
mp[root] =
1
;
//怎么记录flag????
root = root->left;
}
while
(!s.empty() && mp[s.top()]==
2
){
v.push_back(s.top()->val);
s.pop();
}
if
(!s.empty()){
mp[s.top()] =
2
;
root = s.top()->right;
}
}
return
v;
}
};
- 添加笔记
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//=====================递归方法istrivial。不过还是写出来吧=================================
class
Solution {
public
:
void
postOrder(TreeNode *root,vector<
int
>&vec){
if
(root != NULL){
postOrder(root->left,vec);
postOrder(root->right,vec);
vec.push_back(root->val);
}
}
vector<
int
> postorderTraversal(TreeNode *root) {
vector<
int
>vec;
postOrder(root,vec);
return
vec;
}
};
0 0
- binary-tree-postorder-traversal(后序遍历二叉树)
- Binary Tree Postorder Traversal-二叉树的后序遍历
- Binary Tree Postorder Traversal 二叉树的后序遍历
- 二叉树的后序遍历 Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal 二叉树的后序遍历
- Binary Tree Postorder Traversal --二叉树非递归后序遍历(重重)
- LeetCode OJ 之 Binary Tree Postorder Traversal (二叉树的后序遍历)
- Binary Tree Postorder Traversal 二叉树的后序遍历(迭代非递归版本)
- 【leetcode】145Binary Tree Postorder Traversal(二叉树非递归后序遍历)
- 68.Binary Tree Postorder Traversal-二叉树的后序遍历(容易题)
- Construct Binary Tree from Inorder and Postorder Traversal 中序和后序遍历二叉树
- LeetCode Binary Tree Postorder Traversal(二叉树的后序遍历 非递归实现)
- Binary Tree Postorder Traversal 二叉树的后序遍历,使用堆栈,非递归
- LintCode Binary Tree Postorder Traversal 二叉树的后序遍历
- LeetCode 145: Binary Tree Postorder Traversal(二叉树的后序遍历,迭代法)
- LeetCode 145 Binary Tree Postorder Traversal (后序遍历二叉树)
- 【二叉树】后序遍历【Add to List 145. Binary Tree Postorder Traversal】
- [LeetCode]145. Binary Tree Postorder Traversal--二叉树的后序遍历
- Android实现ListView异步加载图片的方法
- poj 1753 Flip Game
- 数据库知识点2
- codeforces 501B B. Misha and Changing Handles
- IT 概率面试题整理
- binary-tree-postorder-traversal(后序遍历二叉树)
- LEETCODE之Different Ways to Add Parentheses
- android listview异步加载图片
- EL表达式
- 数据库知识点3
- TK1时间同步
- hdu2035 人见人爱A^B
- 数据库知识点4
- BZOJ 1485 [HNOI2009]有趣的数列