## [257\. Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_. A **leaf** is a node with no children. **Example 1:** ![](https://assets.leetcode.com/uploads/2021/03/12/paths-tree.jpg) **Input:** root = \[1,2,3,null,5\] **Output:** \["1->2->5","1->3"\] **Example 2:** **Input:** root = \[1\] **Output:** \["1"\] **Constraints:** - The number of nodes in the tree is in the range `[1, 100]`. - `-100 <= Node.val <= 100` recursion ```cpp= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; dfs(root, "", res); return res; } void dfs(TreeNode* root, string out, vector<string>& res) { if(!root->left && !root->right) { res.push_back(out + to_string(root->val)); } if(root->left) { dfs(root->left, out + to_string(root->val) + "->", res); } if(root->right) { dfs(root->right, out + to_string(root->val) + "->", res); } } }; ``` :::success - 時間複雜度:$O(N)$ - 空間複雜度:$O(N)$ ::: iteration ```cpp= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; // base case if(!root) return res; // 如果沒有左右子節點,則返回 root if(!root->left && !root->right) { return {to_string(root->val)}; } // 找左側 for(auto s : binaryTreePaths(root->left)) { res.push_back(to_string(root->val) + "->" + s); } // 找右側 for(auto s : binaryTreePaths(root->right)) { res.push_back(to_string(root->val) + "->" + s); } return res; } }; ``` :::success - 時間複雜度:$O(N)$ - 空間複雜度:$O(N)$ :::