- # 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
- class Solution:
- def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
- def isornot(root: Optional[TreeNode], targetSum: int) -> bool:
- if (not root.left) and (not root.right) and targetSum == 0:
- return True
- if (not root.left) and (not root.right):
- return False
- if root.left:
- if isornot(root.left, targetSum - root.left.val): return True
- if root.right:
- if isornot(root.right, targetSum - root.right.val): return True
- return False
-
- if root == None:
- return False
- else:
- return isornot(root, targetSum - root.val)
解题思路:
1.注意targetsum的用法:每经过一个节点,就将其减去当前经过的节点值,如此到根节点,就正好为0
2.targetSum - root.left.val 中隐藏着回溯思想
3.递归函数参数为root、targetSum & 返回值为bool
4.递归结束条件:判断到叶子节点时,targetSum是否为0;yes则返回true,反之返回false
5.单层递归逻辑:若root左右孩子不为空,则依次继续递归。
if isornot(): return true 会一层一层向上返回true,直到第一层递归。