# 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); } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up