-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Tree_Inorder_Traversal.cpp
More file actions
96 lines (91 loc) · 2.74 KB
/
Binary_Tree_Inorder_Traversal.cpp
File metadata and controls
96 lines (91 loc) · 2.74 KB
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
96
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//O(N)
//O(N)
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> res;
worker(root,res);
return res;
}
void worker(TreeNode* root,vector<int> &vec)
{
if(root==NULL)return;
worker(root->left,vec);
vec.push_back(root->val);
worker(root->right,vec);
}
vector<int> inorderTraversal(TreeNode *node) {
vector<int> result;
if (node == NULL) return result;
stack<TreeNode*> stk;
TreeNode* curr = node;
while (!stk.empty() || curr != NULL) {
if (curr != NULL) {
stk.push(curr);
curr = curr->left;
}
else {
curr = stk.top();
stk.pop();
result.push_back(curr->val);
curr = curr->right;
}
}
return result;
}
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
if(!root)return result;
stack<TreeNode*> stk;
while(!stk.empty()||root!=NULL)
{
if(root)
{
stk.push(root);
root=root->left;
}
else
{
TreeNode* tmp=stk.top();
if(!(tmp->right)||!result.empty()&&result[result.size()-1]==tmp->right->val)
{
result.push_back(tmp->val);
stk.pop();
}
else
{
root=tmp->right;
}
}
}
return result;
}
vector<int> preorderTraversal(TreeNode *node)
{
vector<int> result;
if(node==NULL)return result;
stack<TreeNode *>stk;
stk.push(node);
while(!stk.empty())
{
TreeNode* curr=stk.top();
stk.pop();
result.push_back(curr);
if(curr->right)
stk.push(curr->right);
if(curr->left)
stk.push(curr->left);
}
}
};