## [LeetCode 解题报告]144. Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.

Example:

```Input: `[1,null,2,3]`
1
\
2
/
3

Output: `[1,2,3]`
```

Follow up: Recursive solution is trivial, could you do it iteratively?

Method 1. Recursive

``````/**
* 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> res;
preorderTraversal(root, res);
return res;
}

void preorderTraversal(TreeNode* root, vector<int>& res) {
if (root == NULL)
return ;

res.push_back(root->val);
if (root->left)
preorderTraversal(root->left, res);
if (root->right)
preorderTraversal(root->right, res);
}
};``````

Method 2.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) {
if (root == NULL)
return {};

stack<TreeNode*> s{{root}};
vector<int> res;

while(!s.empty()) {
TreeNode* cur = s.top();
s.pop();
res.push_back(cur->val);

if (cur->right)
s.push(cur->right);
if (cur->left)
s.push(cur->left);
}
return res;
}
};``````

完，