-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary Tree Inorder Traversal LC-94.cpp
95 lines (88 loc) · 2.1 KB
/
Binary Tree Inorder Traversal LC-94.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
// morris traversal
// tc=O(n)
// sc=o(1)
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> res;
TreeNode* curr=root;
TreeNode* prev;
while(curr){
if(curr->left){
prev=curr->left;
while(prev->right && prev->right!=curr){
prev=prev->right;
}
if(prev->right==curr){
res.push_back(curr->val);
prev->right=NULL;
curr=curr->right;
}else{
prev->right=curr;
curr=curr->left;
}
}else{
res.push_back(curr->val);
curr=curr->right;
}
}
return res;
}
};
// tc=O(n)
// sc=o(h)
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> res;
stack<TreeNode*> stk;
stk.push(root);
root=root->left;
while(true){
if(root){
stk.push(root);
root=root->left;
}else{
if(stk.empty()) break;
TreeNode* node = stk.top();
stk.pop();
res.push_back(node->val);
root=node->right;
}
}
return res;
}
};
// tc=O(n)
// sc=o(h)
class Solution {
public:
vector<int> res;
void solve(TreeNode* root){
if(!root) return;
solve(root->left);
res.push_back(root->val);
solve(root->right);
}
vector<int> inorderTraversal(TreeNode* root) {
solve(root);
return res;
}
};
class Solution {
public:
vector<int> solve(TreeNode* root,vector<int> &res){
if(!root) return res;
solve(root->left, res);
res.push_back(root->val);
solve(root->right, res);
return res;
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
solve(root, res);
return res;
}
};