mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +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:
|
||||
"""二叉树的所有路径 递归法"""
|
||||
|
||||
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
|
||||
|
||||
|
||||
@ -457,7 +465,8 @@ class Solution:
|
||||
|
||||
return result
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
Go:
|
||||
```go
|
||||
@ -482,7 +491,7 @@ func binaryTreePaths(root *TreeNode) []string {
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
JavaScript:
|
||||
|
||||
1.递归版本
|
||||
|
Reference in New Issue
Block a user