-
Notifications
You must be signed in to change notification settings - Fork 0
/
200212-2.cpp
58 lines (53 loc) · 1 KB
/
200212-2.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
// https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
// 进阶:使用迭代算法(而非递归算法)
#include <cstdio>
#include <vector>
using namespace std;
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> a;
vector<TreeNode*> stack;
TreeNode* p = root;
for (;;) {
for (; p; p = p->left) {
a.push_back(p->val);
stack.push_back(p);
}
if (stack.empty()) break;
p = stack.back()->right;
stack.pop_back();
}
return a;
}
};
void release(TreeNode* t)
{
if (t) {
release(t->left);
release(t->right);
delete t;
}
}
void print(const vector<int>& a)
{
printf("[ "); for (auto e : a) printf("%d ", e); printf("]\n");
}
int main()
{
Solution s;
{
TreeNode* t = new TreeNode(1);
t->right = new TreeNode(2);
t->right->left = new TreeNode(3);
print(s.preorderTraversal(t));
release(t);
}
return 0;
}