# [leetcode] Binary Tree Preorder Traversal

### Binary Tree Preorder Traversal

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?

tag: stack

```/**
* Definition for binary tree
* 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> re;
_preorderTraversal(re, root);
return re;
}
void _preorderTraversal(vector<int> &re, TreeNode *root){
if(root == NULL){
return;
}
re.push_back(root->val);
_preorderTraversal(re, root->left);
_preorderTraversal(re, root->right);
}
};```

```/**
* Definition for binary tree
* 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> re;
TreeNode * p;;
stack<TreeNode *> s;
s.push(root);
while(!s.empty()){
p = s.top();
s.pop();
if(p == NULL){
continue;
}
re.push_back(p->val);
s.push(p->right);
s.push(p->left);
}
return re;
}
};```

This site uses Akismet to reduce spam. Learn how your comment data is processed.