> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/144.-binary-tree-preorder-traversal-medium.md).

# 144. Binary Tree Preorder Traversal

## 1.問題

* 給予一個binary tree, 回傳pre-order traversal得到的值

![](/files/-LIKqO48nWWSGwwXyG3z)

## 2.想法

* pre-order traversal

## 3.程式碼

```
/**
 * 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) {
        vector<int> v;
        preOrder(v, root);
        return v;
    }
private:
    void preOrder(vector<int>& v, TreeNode* root) {
        if (!root) {
            return;
        }
        v.push_back(root->val);
        preOrder(v, root->left);
        preOrder(v, root->right);
    }
};
```

## 4.Performance

![](/files/-LIKqmXphpONDPmDlDVe)
