###### tags: `Leetcode` `easy` `tree` `dfs` `python` `c++`
# 257. Binary Tree Paths
## [題目連結:] https://leetcode.com/problems/binary-tree-paths/description/
## 題目:
Given the ```root``` of a binary tree, return all root-to-leaf paths in **any order**.
A **leaf** is a node with no children.


## 解題想法:
* 此題為輸出二元樹的所有路徑,並以"->"串接
* DFS遞歸即可:
* Sol1: 直接用原函式遞迴
* 初始需判斷是否為空or沒左右子
* 遞迴左右子創建path
* 將當前root分別與遞迴左右子的結果串接
* merge兩段即為解
* Sol2: 額外寫DFS遞迴
* 原函式給input:
* path=""
* res=[] (或可以用self.res)
* dfs
* 初始判斷root是否為空:
* 空則直接return nothinh
* path+=str(root.val)
* 再判斷是否左右子皆空:
* 若皆空則將該path加入res並return
* 遞迴左子:
* dfs(root.left, path+"->")
* 遞迴右子:
* dfs(root.right, path+"->")
## Python: Sol1
``` python=
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
leftPath=self.binaryTreePaths(root.left)
rightPath=self.binaryTreePaths(root.right)
#字串包在一起 用+ ex: '1'+'->'+'2' = '1->2'
leftMerge=[str(root.val)+"->"+ val for val in leftPath]
rightMerge=[str(root.val)+"->"+val for val in rightPath]
return leftMerge+rightMerge
```
## Python: Sol2
``` python=
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
self.res=[]
path=""
self.dfs(root, path)
return self.res
def dfs(self, root, path):
if not root:
return
path+=str(root.val)
if not root.left and not root.right:
self.res.append(path)
return
if root.left:
self.dfs(root.left, path+"->")
if root.right:
self.dfs(root.right, path+"->")
return
```
## C++: Sol1:
``` cpp=
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
if (!root) return {};
if (!root->left && !root->right) return {to_string(root->val)};
vector<string> LeftPath, RightPath;
LeftPath=binaryTreePaths(root->left);
RightPath=binaryTreePaths(root->right);
//merge LeftPath and RightPath
for (string item: RightPath){
LeftPath.push_back(item);
}
//add "root->val"+"->" in front of all string in LeftPath
for (string& item: LeftPath){
item= to_string(root->val)+"->"+item;
}
return LeftPath;
}
};
```
## C++: Sol2
``` cpp=
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
string path="";
dfs(root, res, path);
return res;
}
void dfs(TreeNode* root, vector<string>& res, string path){
if (root==nullptr) return;
path+=to_string(root->val);
if (!root->left && !root->right){
res.push_back(path);
return;
}
if (root->left) dfs(root->left, res, path+"->");
if (root->right) dfs(root->right, res, path+"->");
return ;
}
};
```