-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_tree_preorder_traversal.cpp
74 lines (62 loc) · 1.41 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
63
64
65
66
67
68
69
70
71
72
73
74
// https://oj.leetcode.com/problems/binary-tree-preorder-traversal/
// Date: Nov 10, 2014
#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:
// iterative traversal
vector<int> preorderTraversal(TreeNode *root)
{
vector<int> vec;
if (root == NULL)
{
return vec;
}
stack<TreeNode* > stk;
stk.push(root);
while (!stk.empty())
{
TreeNode* node = stk.top();
stk.pop();
vec.push_back(node->val);
if (node->right)
{
stk.push(node->right);
}
if (node->left)
{
stk.push(node->left);
}
}
return vec;
}
};
TreeNode* create_binary_tree()
{
TreeNode* root = new TreeNode(3);
TreeNode* node = new TreeNode(9);
root->left = node;
node = new TreeNode(20);
root->right = node;
TreeNode* leftNode = new TreeNode(15);
TreeNode* rightNode = new TreeNode(7);
node->left = leftNode;
node->right = rightNode;
return root;
}
int main(int argc, char* argv[])
{
TreeNode* root = create_binary_tree();
Solution sln;
vector<int> vec = sln.preorderTraversal(root);
return 0;
}