forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Tree_Inorder_Traversal.cc
77 lines (75 loc) · 2.11 KB
/
Binary_Tree_Inorder_Traversal.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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> ans;
if (root == NULL) {
return ans;
}
stack<TreeNode *> st;
stack<bool> flag;
st.push(root);
flag.push(false);
TreeNode *cntNode = NULL;
bool state;
while (!st.empty()) {
cntNode = st.top();
state = flag.top();
flag.pop();
if (state == false) {
flag.push(true);
if (cntNode->left) {
st.push(cntNode->left);
flag.push(false);
}
} else {
st.pop();
ans.push_back(cntNode->val);
if (cntNode->right) {
st.push(cntNode->right);
flag.push(false);
}
}
}
return ans;
}
};
//O(1) space algorithm
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> ret;
TreeNode *pre = NULL;
TreeNode *cur = root;
while (cur) {
if (!cur->left) {
ret.push_back(cur->val);
cur = cur->right;
} else {
pre = cur->left;
while (pre->right && pre->right != cur) pre = pre->right;
if (pre->right == NULL) {
pre->right = cur;
cur = cur->left;
} else {
pre->right = NULL;
ret.push_back(cur->val);
cur = cur->right;
}
}
}
return ret;
}
};