-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreeTraversalsConstantSpace.cpp
49 lines (48 loc) · 1.53 KB
/
BinaryTreeTraversalsConstantSpace.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
vector < int > inorderMorrisTraversal(TreeNode * root) {
vector < int > res;
if (!root) return res;
TreeNode *cur, * pre;
cur = root;
while (cur) {
if (!cur-> left) {
res.push_back(cur -> val);
cur = cur-> right;
} else {
pre = cur-> left;
while (pre->right && pre->right != cur) pre = pre-> right;
if (!pre-> right) {
pre ->right = cur;
cur = cur-> left;
} else {
pre ->right = NULL;
res.push_back(cur -> val);
cur = cur-> right;
}
}
}
return res;
}
vector < int > preorderMorrisTraversal(TreeNode * root) {
vector < int > res;
if (!root) return res;
TreeNode *cur, * pre;
cur = root;
while (cur) {
if (!cur-> left) {
res.push_back(cur -> val);
cur = cur-> right;
} else {
pre = cur-> left;
while (pre->right && pre->right != cur) pre = pre-> right;
if (!pre-> right) {
pre ->right = cur;
res.push_back(cur -> val); // only difference with inorder
cur = cur-> left;
} else {
pre ->right = NULL;
cur = cur-> right;
}
}
}
return res;
}