-
Notifications
You must be signed in to change notification settings - Fork 0
/
145-BinaryTreePostorderTraversal.cc
79 lines (74 loc) · 1.82 KB
/
145-BinaryTreePostorderTraversal.cc
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
78
79
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*
递归版,so easy
*/
class Solution
{
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> result;
postorderHelp(root, result);
return result;
}
private:
void postorderHelp(TreeNode *root, vector<int> &nodes)
{
if (root == nullptr)
return;
postorderHelp(root->left, nodes);
postorderHelp(root->right, nodes);
nodes.push_back(root->val);
}
};
/*
非递归版,有点难,还是用到栈,不过元素是一个pair,first是结点指针,second是方向
*/
class Solution
{
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> result;
if (root == nullptr)
return result;
stack<pair<TreeNode *, char>> s;
TreeNode *node = root;
do
{
while (node != nullptr)
{
s.push(make_pair(node, 'L'));
node = node->left;
}
bool shouldContinue = true;
while (shouldContinue && !s.empty())
{
auto pair = s.top();
s.pop();
node = pair.first;
switch (pair.second)
{
case 'L':
pair.second = 'R';
s.push(pair);
shouldContinue = false;
node = node->right;
break;
case 'R':
result.push_back(pair.first->val);
break;
}
}
} while (!s.empty());
return result;
}
};