-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLeetcode_binary-tree-inorder-traversal.cc
87 lines (85 loc) · 2.08 KB
/
Leetcode_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
78
79
80
81
82
83
84
85
86
87
/**
* 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) {
vector<int>res;
if(root)
{
stack<TreeNode*>s;
s.push(root);
while(!s.empty())
{
while(root->left)
{
root = root->left;
s.push(root);
}
root = s.top();
res.push_back(root->val);
if(root->right)
{
root = root->right;
s.pop();
s.push(root);
}
else
{
s.pop();
while(!s.empty() && !s.top()->right)
{
res.push_back(s.top()->val);
s.pop();
}
if(!s.empty())
{
res.push_back(s.top()->val);
root = s.top()->right;
s.pop();
s.push(root);
}
}
}
}
return res;
}
};
//SECOND TRIAL
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int>ans;
stack<TreeNode*>st;
TreeNode *p = root;
while(p)
{
while(p)
{
st.push(p);
p = p->left;
}
if(!st.empty())
{
while(!st.empty() && !st.top()->right)
{
ans.push_back(st.top()->val);
st.pop();
}
if(st.empty())
break;
p = st.top();
ans.push_back(p->val);
st.pop();
p = p->right;
}
}
return ans;
}
};