-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary Tree Preorder Traversal LC-144.cpp
62 lines (62 loc) · 1.43 KB
/
Binary Tree Preorder Traversal LC-144.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
// tc=O(n)
// sc=o(n)
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> res;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* node = stk.top();
res.push_back(node->val);
stk.pop();
if(node->right){
stk.push(node->right);
}if(node->left){
stk.push(node->left);
}
}
return res;
}
};
// tc=O(n)
// sc=o(n)
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> res;
stack<TreeNode*> stk;
while(true){
if(root){
res.push_back(root->val);
stk.push(root);
root=root->left;
}else{
if(stk.empty()) break;
TreeNode* temp=stk.top();
stk.pop();
root=temp->right;
}
}
return res;
}
};
// tc=O(n)
// sc=o(h)
class Solution {
public:
vector<int> solve(TreeNode* root, vector<int>& res){
if(!root) return res;
res.push_back(root->val);
solve(root->left, res);
solve(root->right, res);
return res;
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
solve(root,res);
return res;
}
};