Skip to content

Commit

Permalink
Merge pull request youngyangyang04#813 from casnz1601/patch-2
Browse files Browse the repository at this point in the history
Update 0257.二叉树的所有路径.md
  • Loading branch information
youngyangyang04 authored Oct 5, 2021
2 parents a08aacd + f1aa928 commit c7da945
Showing 1 changed file with 26 additions and 17 deletions.
43 changes: 26 additions & 17 deletions problems/0257.二叉树的所有路径.md
Original file line number Diff line number Diff line change
Expand Up @@ -404,33 +404,41 @@ class Solution {
}
}
```

Python:
```Python
---
Python:
递归法+隐形回溯
```Python3
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
"""二叉树的所有路径 递归法"""

def binaryTreePaths(self, root: TreeNode) -> List[str]:
path, result = '', []
path = ''
result = []
if not root: return result
self.traversal(root, path, result)
return result

def traversal(self, cur: TreeNode, path: List, result: List):
def traversal(self, cur: TreeNode, path: str, result: List[str]) -> None:
path += str(cur.val)
# 如果当前节点为叶子节点,添加路径到结果中
if not (cur.left or cur.right):
# 若当前节点为leave,直接输出
if not cur.left and not cur.right:
result.append(path)
return


if cur.left:
# + '->' 是隐藏回溯
self.traversal(cur.left, path + '->', result)

if cur.right:
self.traversal(cur.right, path + '->', result)

```

```python

迭代法:

```python3
from collections import deque


Expand All @@ -457,7 +465,8 @@ class Solution:

return result
```


---

Go:
```go
Expand All @@ -482,7 +491,7 @@ func binaryTreePaths(root *TreeNode) []string {
return res
}
```

---
JavaScript:

1.递归版本
Expand Down

0 comments on commit c7da945

Please sign in to comment.