-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary Tree Preorder Traversal.cpp
62 lines (61 loc) · 1.35 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//////recursive solution;
class Solution {
public:
vector<int> val;
vector<int> preorderTraversal(TreeNode* root) {
function(root,val);
return val;
}
void function(TreeNode* root,vector<int> &val)
{
if(root==NULL)
return;
val.push_back(root->val);
function(root->left,val);
function(root->right,val);
}
};
//iteratively
/**
* 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) {
stack<TreeNode*> stk;
vector<int> results;
while(!stk.empty() || root!=NULL)
{
if(root!=NULL)
{
results.push_back(root->val);
if(root->right!=NULL)
{
stk.push(root->right);
}
root=root->left;
}
else
{
root=stk.top();
stk.pop();
}
}
return results;
}
};