-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-tree-preorder-traversal.cpp
41 lines (41 loc) · 1.09 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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class MySafeStack : public stack<pair<TreeNode*, int> > {
public:
void guard_push(pair<TreeNode*, int> pairData) {
if (pairData.first)
this->push(pairData);
}
};
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> result;
if (root == nullptr) return result;
MySafeStack trace;
trace.guard_push({root, 0});
while (!trace.empty()) {
TreeNode *cur = trace.top().first;
int &stage = trace.top().second;
if (stage == 0) {
result.push_back(cur->val);
trace.guard_push({cur->left, 0});
}
else if (stage == 1) {
trace.guard_push({cur->right, 0});
}
else {
trace.pop();
}
stage++;
}
return result;
}
};