-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Tree_Postorder_Traversal.cpp
More file actions
77 lines (68 loc) · 1.74 KB
/
Binary_Tree_Postorder_Traversal.cpp
File metadata and controls
77 lines (68 loc) · 1.74 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Source : https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
// Author : zheng yi xiong
// Date : 2014-11-22
/**********************************************************************************
*
* 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?
*
**********************************************************************************/
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> postorder_vec;
if (NULL == root)
{
return postorder_vec;
}
stack<TreeNode *> postorder_stack;
vector<bool> bVisit_vec; //if visit stack node
postorder_stack.push(NULL);
postorder_stack.push(root);
bVisit_vec.push_back(false);
TreeNode *pTempNode = postorder_stack.top();
int visit_index = 0;
while (NULL != pTempNode)
{
if ( (bVisit_vec[visit_index]) || ((NULL == pTempNode->right) && (NULL == pTempNode->left)) )
{
postorder_vec.push_back(pTempNode->val);
postorder_stack.pop();
bVisit_vec.pop_back();
--visit_index;
}
else
{
bVisit_vec[visit_index] = true;
if (NULL != pTempNode->right)
{
postorder_stack.push(pTempNode->right);
bVisit_vec.push_back(false);
++visit_index;
}
if (NULL != pTempNode->left)
{
postorder_stack.push(pTempNode->left);
bVisit_vec.push_back(false);
++visit_index;
}
}
pTempNode = postorder_stack.top();
}
return postorder_vec;
}
};