mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
@ -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:
|
class Solution:
|
||||||
"""二叉树的所有路径 递归法"""
|
|
||||||
|
|
||||||
def binaryTreePaths(self, root: TreeNode) -> List[str]:
|
def binaryTreePaths(self, root: TreeNode) -> List[str]:
|
||||||
path, result = '', []
|
path = ''
|
||||||
|
result = []
|
||||||
|
if not root: return result
|
||||||
self.traversal(root, path, result)
|
self.traversal(root, path, result)
|
||||||
return 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)
|
path += str(cur.val)
|
||||||
# 如果当前节点为叶子节点,添加路径到结果中
|
# 若当前节点为leave,直接输出
|
||||||
if not (cur.left or cur.right):
|
if not cur.left and not cur.right:
|
||||||
result.append(path)
|
result.append(path)
|
||||||
return
|
|
||||||
|
|
||||||
if cur.left:
|
if cur.left:
|
||||||
|
# + '->' 是隐藏回溯
|
||||||
self.traversal(cur.left, path + '->', result)
|
self.traversal(cur.left, path + '->', result)
|
||||||
|
|
||||||
if cur.right:
|
if cur.right:
|
||||||
self.traversal(cur.right, path + '->', result)
|
self.traversal(cur.right, path + '->', result)
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
迭代法:
|
||||||
|
|
||||||
|
```python3
|
||||||
from collections import deque
|
from collections import deque
|
||||||
|
|
||||||
|
|
||||||
@ -458,6 +466,7 @@ class Solution:
|
|||||||
return result
|
return result
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
```go
|
```go
|
||||||
@ -482,7 +491,7 @@ func binaryTreePaths(root *TreeNode) []string {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
---
|
||||||
JavaScript:
|
JavaScript:
|
||||||
|
|
||||||
1.递归版本
|
1.递归版本
|
||||||
|
Reference in New Issue
Block a user