> 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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LSCqTCR2_JaOsWW9QlT%2F-LSCrEVFqBCirrspoZVB%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-11-26%20%E4%B8%8A%E5%8D%8810.32.45.png?alt=media\&token=eba48a03-ef33-462f-b5d7-43d0dc2504d2)

## 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);
            
        }
    }
};
```
