题解 | #二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
https://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
class Solution: def hasPathSum(self , root: TreeNode, sum: int) -> bool: def preOder(root, res): if not root: # 如果无子节点且res等于sum,则返回true return False # 如果节点为空说明此路径在上一步递归已经被淘汰掉了 res += root.val if not root.left and not root.right and res == sum: return True return preOder(root.left, res) or preOder(root.right, res) return False if not root else preOder(root, 0)