Update 0257.二叉树的所有路径.md

This commit is contained in:
jianghongcheng
2023-05-22 16:48:27 -05:00
committed by GitHub
parent f5329cd4b9
commit 2024fc272a

View File

@ -473,31 +473,27 @@ class Solution {
递归法+回溯(版本一) 递归法+回溯(版本一)
```Python ```Python
# Definition for a binary tree node. # 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: class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: def traversal(self, cur, path, result):
if not root: path.append(cur.val) # 中
return [] if not cur.left and not cur.right: # 到达叶子节点
result = [] sPath = '->'.join(map(str, path))
self.generate_paths(root, [], result) result.append(sPath)
return result return
if cur.left: # 左
self.traversal(cur.left, path, result)
path.pop() # 回溯
if cur.right: # 右
self.traversal(cur.right, path, result)
path.pop() # 回溯
def generate_paths(self, node: TreeNode, path: List[int], result: List[str]) -> None: def binaryTreePaths(self, root):
path.append(node.val) result = []
if not node.left and not node.right: path = []
result.append('->'.join(map(str, path))) if not root:
if node.left: return result
self.generate_paths(node.left, copy.copy(path), result) self.traversal(root, path, result)
if node.right: return result
self.generate_paths(node.right, copy.copy(path), result)
path.pop()
``` ```