-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0590_postorder.cc
81 lines (72 loc) · 1.14 KB
/
Problem_0590_postorder.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
80
81
#include <algorithm>
#include <stack>
#include <vector>
using namespace std;
class Node
{
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) { val = _val; }
Node(int _val, vector<Node*> _children)
{
val = _val;
children = _children;
}
};
class Solution
{
private:
void f(Node* cur, vector<int>& ans)
{
if (cur == nullptr)
{
return;
}
for (auto& c : cur->children)
{
f(c, ans);
}
ans.push_back(cur->val);
}
public:
// 递归
vector<int> postorder(Node* root)
{
vector<int> ans;
f(root, ans);
return ans;
}
// 非递归
vector<int> iterative(Node* root)
{
if (root == nullptr)
{
return {};
}
vector<int> ans;
stack<Node*> stA;
stack<Node*> stB;
stA.push(root);
while (!stA.empty())
{
Node* cur = stA.top();
stA.pop();
// 根 右 左
stB.push(cur);
for (auto& c : cur->children)
{
stA.push(c);
}
}
while (!stB.empty())
{
// 左 右 根
Node* cur = stB.top();
stB.pop();
ans.push_back(cur->val);
}
return ans;
}
};