# \#257 Binary Tree Paths
## *解析二元樹的所有路徑(從root到leaf, leaf指沒有左節點及右節點)*
## Log
- build 20210527 by syhuang
## 一般解
- 一般解法(dfs深度優先)
```javascript=
var binaryTreePaths = function(root) {
var result = [];
var pathObj = [{node:root,path:''}];//暫存目前經過node及所有val
while(pathObj.length>0){
var n = pathObj.pop();
var tn = n.node;
var tpath = n.path;
if(!tn.left && !tn.right) result.push(tpath+tn.val);
if(tn.right) pathObj.push({node:tn.right,path:tpath+tn.val+'->'});
if(tn.left) pathObj.push({node:tn.left,path:tpath+tn.val+'->'});
}
return result;
};
```
## 初見
- 遞迴解, 空間複雜度較高
```javascript=
var binaryTreePaths = function(root) {
var result = [];
pathThrough(root,'',result);
return result;
function pathThrough(node,path,allPath){
if(!node.left && !node.right) allPath.push(path+node.val+'');//node is leaf
if(node.left) pathThrough(node.left,path+node.val+'->',allPath);
if(node.right) pathThrough(node.right,path+node.val+'->',allPath);
};
};
```
## 備註
- 初見時嘗試用一般解(非遞迴解)但沒做出來qq
## 參考
- [遞迴解參考](https://leetcode.com/problems/binary-tree-paths/discuss/68258/Accepted-Java-simple-solution-in-8-lines)
- [dfs/bfs/遞迴等多種解](https://leetcode.com/problems/binary-tree-paths/discuss/68272/Python-solutions-(dfs%2Bstack-bfs%2Bqueue-dfs-recursively).)
###### tags: `leetcode`, `leetcode-easy`, `binary tree`