---
# System prepended metadata

title: 257. Binary Tree Paths
tags: [C++, LeetCode]

---

# LeetCode 257. Binary Tree Paths

https://leetcode.com/problems/binary-tree-paths/description/

## 題目大意

給二元樹的 `root` ，回傳所有 `root` 到 `leaf` 的路徑 (任意順序)

## 思考

這題很簡單，就用一個 string `path` 來記錄路徑
走到 `leaf` 再塞進 `ans` 裡

至於走法，就用遞迴一直往左往右，沒什麼好說的

```C++
class Solution
{
public:
    vector<string> binaryTreePaths(TreeNode *root)
    {
        vector<string> ans;
        helper(root, "", ans);
        return ans;
    }

private:
    void helper(TreeNode *node, string path, vector<string> &ans)
    {
        if (!node)
            return;

        if (!path.empty())
            path += "->";

        path += to_string(node->val);

        if (!node->left && !node->right)
        {
            ans.emplace_back(path);
            return;
        }

        helper(node->left, path, ans);
        helper(node->right, path, ans);
    }
};
```