forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path144.binary-tree-preorder-traversal.cpp
61 lines (53 loc) · 1.23 KB
/
144.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
/**
* 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) {
if (root == NULL)
{
return vector<int>();
}
vector<int> res;
stack<TreeNode *> s;
s.push(root);
while (!s.empty()) {
TreeNode *node = s.top();
s.pop();
res.push_back(node->val);
if (node->right)
{
s.push(node->right);
}
if (node->left)
{
s.push(node->left);
}
}
return res;
}
};
class Solution2 {
private:
void helper(TreeNode* node, vector<int> &result){
if (node == NULL)
{
return;
}
result.push_back(node->val);
helper(node->left, result);
helper(node->right, result);
}
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
helper(root, res);
return res;
}
};