forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-tree-preorder-traversal.cpp
84 lines (79 loc) · 1.96 KB
/
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
// Time: O(n)
// Space: O(1)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
// Morris Traversal.
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
vector<int> preorderTraversal(TreeNode *root) {
vector<int> res;
TreeNode *prev = nullptr;
TreeNode *curr = root;
while (curr) {
if (!curr->left) {
res.emplace_back(curr->val);
prev = curr;
curr = curr->right;
} else {
TreeNode *node = curr->left;
while (node->right && node->right != curr) {
node = node->right;
}
if (!node->right) {
res.emplace_back(curr->val);
prev = curr;
node->right = curr;
curr = curr->left;
} else {
node->right = nullptr;
curr = curr->right;
}
}
}
return res;
}
};
// Time: O(n)
// Space: O(h)
// Stack solution.
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
vector<int> preorderTraversal(TreeNode *root) {
if (!root) {
return {};
}
stack<TreeNode *> s;
s.emplace(root);
vector<int> res;
while (!s.empty()) {
auto curr = s.top();
s.pop();
res.emplace_back(curr->val);
if (curr->right) {
s.emplace(curr->right);
}
if (curr->left) {
s.emplace(curr->left);
}
}
return res;
}
};