0
点赞
收藏
分享

微信扫一扫

257. 二叉树的所有路径


文章目录

  • ​​Question​​
  • ​​Ideas​​
  • ​​Code​​

Question

​​257. 二叉树的所有路径​​

Ideas

递归

  • 终止条件:遍历到叶子节点
    if not root.left and not root.right: # 当前节点是叶子节点
    paths.append(path) # 把路径加入到答案中
  • 参数:当前节点和到当前节点的路径 无需返回值
  • 单层逻辑:遍历其左右子树
    construct_paths(root.left, path)
    construct_paths(root.right, path)

Code

class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
def construct_paths(root, path):
if root:
path += str(root.val)
if not root.left and not root.right: # 当前节点是叶子节点
paths.append(path) # 把路径加入到答案中
else:
path += '->' # 当前节点不是叶子节点,继续递归遍历
construct_paths(root.left, path)
construct_paths(root.right, path)

paths = []
construct_paths(root, '')
return paths


举报

相关推荐

0 条评论