
思路
在进行先序遍历时,首先判断递归终止的条件:若当前节点为空,则返回 False;若当前节点为叶子节点,且其值等于目标和,则返回 True。递归的核心逻辑是:分别对左右子树进行递归遍历,并在过程中更新目标和。
python
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
#只有有一条就够了,传入节点和相应的和
def inorder(node,sum):
if node==None:
return False
if node.left==None and node.right==None and node.val==sum:
return True
sum-=node.val
Left=inorder(node.left,sum)
Right=inorder(node.right,sum)
return Left or Right
if not root:
return False
return inorder(root,targetSum)