Problem:
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?
解题思路:
/* 核心思想是用栈做辅助空间,先从根往左一直入栈,直到为空,然后判断栈顶元素的右孩子,如果不为空且未被访问过,
* 则从它开始重复左孩子入栈的过程;否则说明此时栈顶为要访问的节点(因为左右孩子都是要么为空要么已访问过了),
* 出栈然后访问即可,接下来再判断栈顶元素的右孩子...直到栈空。
*/
My Answer:
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
35
36
37
38
39
40
41
42
|
/**
* 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;
if (root == NULL)
return res;
stack<TreeNode*> s;
TreeNode *p, *r=NULL;
p = root; //P记录当前节点,r用来记录上一次访问的节点
//s.push(p);
while (p != NULL || !s.empty()){
if (p){ //左孩子一直入栈,直到为空
s.push(p);
p = p->left;
}
else {
p = s.top();
p = p->right;
if(p && r!=p){ //如果栈顶元素的右孩子不为空,且未被访问过
s.push(p); //则右孩子进栈,然后重复左孩子一直进栈直到为空的过程
p = p->left;
}
else {
r = s.top(); //否则出栈,访问,r记录刚刚访问的节点
res.push_back(r->val);
s.pop();
p = NULL;
}
}
}
return res;
}
};
|