mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-12 05:20:59 +08:00
Update 0257.二叉树的所有路径.md
This commit is contained in:
@ -512,19 +512,19 @@ class Solution:
|
||||
if not root:
|
||||
return []
|
||||
result = []
|
||||
self.generate_paths(root, [], result)
|
||||
self.traversal(root, [], result)
|
||||
return result
|
||||
|
||||
def generate_paths(self, node: TreeNode, path: List[int], result: List[str]) -> None:
|
||||
if not node:
|
||||
def traversal(self, cur: TreeNode, path: List[int], result: List[str]) -> None:
|
||||
if not cur:
|
||||
return
|
||||
path.append(node.val)
|
||||
if not node.left and not node.right:
|
||||
path.append(cur.val)
|
||||
if not cur.left and not cur.right:
|
||||
result.append('->'.join(map(str, path)))
|
||||
else:
|
||||
# path[:] 是隐藏回溯
|
||||
self.generate_paths(node.left, path[:], result)
|
||||
self.generate_paths(node.right, path[:], result)
|
||||
if cur.left:
|
||||
self.traversal(cur.left, path[:], result)
|
||||
if cur.right:
|
||||
self.traversal(cur.right, path[:], result)
|
||||
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user