mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0257.二叉树的所有路径.md
This commit is contained in:
@ -468,6 +468,71 @@ class Solution {
|
||||
```
|
||||
---
|
||||
## Python:
|
||||
|
||||
|
||||
递归法+回溯(版本一)
|
||||
```Python
|
||||
# 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
|
||||
import copy
|
||||
from typing import List, Optional
|
||||
|
||||
class Solution:
|
||||
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
|
||||
if not root:
|
||||
return []
|
||||
result = []
|
||||
self.generate_paths(root, [], result)
|
||||
return result
|
||||
|
||||
def generate_paths(self, node: TreeNode, path: List[int], result: List[str]) -> None:
|
||||
path.append(node.val)
|
||||
if not node.left and not node.right:
|
||||
result.append('->'.join(map(str, path)))
|
||||
if node.left:
|
||||
self.generate_paths(node.left, copy.copy(path), result)
|
||||
if node.right:
|
||||
self.generate_paths(node.right, copy.copy(path), result)
|
||||
path.pop()
|
||||
|
||||
|
||||
```
|
||||
递归法+回溯(版本二)
|
||||
```Python
|
||||
# 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
|
||||
import copy
|
||||
from typing import List, Optional
|
||||
|
||||
class Solution:
|
||||
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
|
||||
if not root:
|
||||
return []
|
||||
result = []
|
||||
self.generate_paths(root, [], result)
|
||||
return result
|
||||
|
||||
def generate_paths(self, node: TreeNode, path: List[int], result: List[str]) -> None:
|
||||
if not node:
|
||||
return
|
||||
path.append(node.val)
|
||||
if not node.left and not node.right:
|
||||
result.append('->'.join(map(str, path)))
|
||||
else:
|
||||
self.generate_paths(node.left, copy.copy(path), result)
|
||||
self.generate_paths(node.right, copy.copy(path), result)
|
||||
path.pop()
|
||||
|
||||
```
|
||||
|
||||
递归法+隐形回溯
|
||||
```Python
|
||||
# Definition for a binary tree node.
|
||||
|
Reference in New Issue
Block a user