如何判断到达叶子(if not root.left and not root.right:)
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
res=[0]
def dfs(root,s):
if not root.left and not root.right:
res[0]+=int(s+str(root.val))
return
if root.left:
dfs(root.left,s+str(root.val))
if root.right:
dfs(root.right,s+str(root.val))
dfs(root,'')
return res[0]

本文介绍了一种使用深度优先搜索(DFS)遍历二叉树的方法,通过递归算法来寻找所有从根节点到叶子节点的路径,并计算这些路径上的数值之和。这种方法适用于解决诸如求解二叉树中所有路径数值之和的问题。
2394

被折叠的 条评论
为什么被折叠?



