-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-tree-preorder-traversal.cpp
69 lines (63 loc) · 1.55 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
/*
* Copyright (c) 2018 Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
public:
// https://leetcode.com/problems/binary-tree-preorder-traversal/
// RECURSIVE
/*
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ret;
if ( nullptr == root ) {
return ret;
}
ret.push_back( root->val );
vector<int> left = preorderTraversal( root->left );
vector<int> right = preorderTraversal( root->right );
for( auto l: left ) {
ret.push_back( l );
}
for( auto r: right ) {
ret.push_back( r );
}
return ret;
}
*/
// NON-RECURSIVE
vector<int> preorderTraversal(TreeNode *root) {
vector<int> ret;
if (nullptr == root) {
return ret;
}
TreeNode *it;
unordered_set<TreeNode *> visited;
vector<TreeNode *> parent;
for (it = root;;) {
if (visited.end() == visited.find(it)) {
visited.insert(it);
ret.push_back(it->val);
}
if (nullptr != it->left && visited.end() == visited.find(it->left)) {
parent.push_back(it);
it = it->left;
continue;
}
if (nullptr != it->right && visited.end() == visited.find(it->right)) {
parent.push_back(it);
it = it->right;
continue;
}
if (parent.empty()) {
break;
}
it = parent.back();
parent.pop_back();
}
return ret;
}
};