-
Notifications
You must be signed in to change notification settings - Fork 3
/
preOrder_and_inorder.cpp
48 lines (46 loc) · 1.24 KB
/
preOrder_and_inorder.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
//前序
vector<int> preorderTraversal2(TreeNode *root) {
// write your code here
vector<int> result;
if(root == NULL) {
return result;
}
stack<TreeNode*> s;
TreeNode * node = root;
s.push(node);
while(!s.empty()) {
node = s.top();
s.pop();
result.push_back(node->val);
if(node->right != NULL) {
s.push(node->right);
}
if(node->left != NULL) {
s.push(node->left);
}
}
return result;
}
//中序
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
vector<int> result;
if(root == NULL) {
return result;
}
stack<TreeNode *> s;
TreeNode * node = root;
while(!s.empty() || node != NULL) {
while(node != NULL) {
s.push(node);
node = node->left;
}
if(!s.empty()) {
node = s.top();
s.pop();
result.push_back(node->val);
node = node->right;
}
}
return result;
}