> 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/257.-binary-tree-paths.md).

# 257. Binary Tree Paths

## 1.問題

* 回傳所有root-to-leaf path

![](/files/-LSCrEVFqBCirrspoZVB)

## 2.想法

* preorder 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<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        vector<int> record;
        preorder(res, record, root);
        return res;
    }
private:
    void preorder(vector<string>& res, vector<int> record, TreeNode* root) {
        if (root) {
            record.push_back(root->val);
            if (!root->left && !root->right) {
                string tmp = to_string(record[0]);
                for (int i = 1; i < record.size(); i++) {
                    tmp = tmp + "->" + to_string(record[i]);
                }
                res.push_back(tmp);
            }
            preorder(res, record, root->left);
            preorder(res, record, root->right);
            
        }
    }
};
```
