-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-pre.cpp
More file actions
38 lines (33 loc) · 833 Bytes
/
binary-tree-pre.cpp
File metadata and controls
38 lines (33 loc) · 833 Bytes
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
// Given a binary tree, return the preorder traversal of its nodes' values.
// For example:
// Given binary tree{1,#,2,3},
// 1
// \
// 2
// /
// 3
// return[1,2,3].
// Note: Recursive solution is trivial, could you do it iteratively?
class Solution{
public:
vector<int> preorderTraversal(TreeNode* root){
vector<int> res;
stack<TreeNode*> s;
if (root == NULL)
{
return res;
}
s.push(root);
while (!s.empty())
{
TreeNode* cur = s.top();
s.pop();
res.push_back(cur->val);
if (cur->right != NULL)
s.push(cur->right);
if (cur->left != NULL)
s.push(cur->left);
}
return res;
}
};