forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
binary-tree-preorder-traversal.cpp
66 lines (64 loc) · 1.65 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
// Time: O(n)
// Space: O(1)
/**
* 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> res;
auto *curr = root;
while (curr) {
if (!curr->left) {
res.emplace_back(curr->val);
curr = curr->right;
} else {
auto *node = curr->left;
while (node->right && node->right != curr) {
node = node->right;
}
if (!node->right) {
res.emplace_back(curr->val);
node->right = curr;
curr = curr->left;
} else {
node->right = nullptr;
curr = curr->right;
}
}
}
return res;
}
};
// Time: O(n)
// Space: O(h)
class Solution2 {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<pair<TreeNode *, bool>> s;
s.emplace(root, false);
while (!s.empty()) {
bool visited;
tie(root, visited) = s.top();
s.pop();
if (root == nullptr) {
continue;
}
if (visited) {
res.emplace_back(root->val);
} else {
s.emplace(root->right, false);
s.emplace(root->left, false);
s.emplace(root, true);
}
}
return res;
}
};