forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
144.cpp
57 lines (46 loc) · 1.12 KB
/
144.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
#include <iostream>
#include <vector>
#include <stack>
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> ret;
if (!root) return ret;
stack<TreeNode *> s;
s.push(root);
while (!s.empty()) {
TreeNode *p = s.top();
s.pop();
if (p) {
ret.push_back(p->val);
s.push(p->right);
s.push(p->left);
}
}
return ret;
}
};
int main() {
TreeNode *root = new TreeNode(4);
TreeNode *p = root;
p->left = new TreeNode(2);
p->right = new TreeNode(5);
p = p->left;
p->left = new TreeNode(1);
p->right = new TreeNode(3);
Solution s;
vector<int> ret = s.preorderTraversal(root);
// should be 42135
for (unsigned int i = 0; i < ret.size(); i++) {
cout << ret[i];
}
cout << endl;
return 0;
}