-
Notifications
You must be signed in to change notification settings - Fork 0
/
fsm.cpp
111 lines (109 loc) · 3.13 KB
/
fsm.cpp
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
#include <stack>
#include <vector>
using std::stack;
using std::vector;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> result;
stack<TreeNode *> st;
if (root != nullptr)
st.push(root);
while (!st.empty()) {
TreeNode *node = st.top();
//对节点进行遍历
if (node != nullptr) {
st.pop(); // 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
if (node->right != nullptr)
st.push(node->right);
st.push(node);
st.push(nullptr);
if (node->left != nullptr)
st.push(node->left);
} else { //依次处理节点
st.pop();
node = st.top();
st.pop();
result.push_back(node->val);
}
}
return result;
}
vector<int> preorderTraversal(TreeNode *root) {
vector<int> result;
stack<TreeNode *> st;
if (root != nullptr)
st.push(root);
while (!st.empty()) {
TreeNode *node = st.top();
if (node != nullptr) {
st.pop();
if (node->right != nullptr)
st.push(node->right);
if (node->left != nullptr)
;
st.push(node->left);
st.push(node);
st.push(nullptr);
} else {
st.pop();
node = st.top();
st.pop();
result.push_back(node->val);
}
}
}
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
stack<TreeNode *> st;
if (root != nullptr)
st.push(root);
while (!st.empty()) {
TreeNode *node = st.top();
if (node != nullptr) {
st.pop();
st.push(node);
st.push(nullptr);
if (node->right != nullptr)
st.push(node->right);
if (node->left != nullptr)
st.push(node->left);
} else {
st.pop();
node = st.top();
st.pop();
result.push_back(node->val);
}
}
}
};
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
stack<TreeNode *> st;
if (root != nullptr)
st.push(root);
while (!st.empty()) {
TreeNode *node = st.top();
if (node != nullptr) {
st.pop();
st.push(node);
st.push(nullptr);
if (node->right != nullptr)
st.push(node->right);
if (node->left != nullptr)
st.push(node->left);
} else {
st.pop();
node = st.top();
st.pop();
result.push_back(node->val);
}
}
}