-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path144-Binary Tree Preorder Traversal.cpp
executable file
·87 lines (78 loc) · 2.22 KB
/
144-Binary Tree Preorder Traversal.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> stk;
TreeNode *cur = root;
while (!stk.empty() || cur != nullptr) {
if (cur != nullptr) {
stk.push(cur);
result.push_back(cur->val);
cur = cur->left;
}
else {
TreeNode *n = stk.top();
stk.pop();
cur = n->right;
}
}
return result;
}
};
// recursive solution
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
preorder(result, root);
return result;
}
private:
void preorder(vector<int> &result, TreeNode *root) {
if (root == nullptr) {
return;
}
result.push_back(root->val);
preorder(result, root->left);
preorder(result, root->right);
}
};
// morris traversal
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
TreeNode *cur = root;
while (cur != nullptr) {
if (cur->left != nullptr) {
TreeNode *predecessor = cur->left;
while (predecessor->right != nullptr && predecessor->right != cur) {
predecessor = predecessor->right;
}
if (predecessor->right == nullptr) {
result.push_back(cur->val);
predecessor->right = cur;
cur = cur->left;
}
else {
predecessor->right = nullptr;
cur = cur->right;
}
}
else {
result.push_back(cur->val);
cur = cur->right;
}
}
return result;
}
};