#112 Path Sum
Given the root
of a binary tree and an integer targetSum
, return true
if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum
.
A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: The root-to-leaf path with the target sum is shown.
Example 2:
Input: root = [1,2,3], targetSum = 5 Output: false Explanation: There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5.
Example 3:
Input: root = [], targetSum = 0 Output: false Explanation: Since the tree is empty, there are no root-to-leaf paths.
Constraints:
[0, 5000]
.-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
解题思路:
刚开始只想到 base case 是左右节点都为空的叶点 leaf node。然后直接返回 该节点值与目标值是否相等的 boolean value。如果左右有一个非空,那么就返回hasPathSum(非空点,目标值-根节点值);如果左右两个子节点都非空,那么就返回hasPathSum(左节点,目标值-根节点值) or hasPathSum(右节点,目标值-根节点值)。
要注意的是,还应该补充一个最base的case,根节点本身为空。那么直接返回 False。另外,因为调用到自己,所以 hasPathSum 前还需要补一个 self.
# 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:
if not root: return False
if root.left == None and root.right == None:
return root.val == targetSum
if root.left == None:
return self.hasPathSum(root.right, targetSum-root.val)
elif root.right == None:
return self.hasPathSum(root.left, targetSum-root.val)
else:
return self.hasPathSum(root.left, targetSum-root.val) or self.hasPathSum(root.right, targetSum-root.val)
Runtime
找了一下最佳的解法
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
# Base case: If node is None, return False
if not root:
return False
# Subtract the value of the current node from target sum
targetSum -= root.val
# If current node is a leaf, check if target sum is 0
if not root.left and not root.right:
return targetSum == 0
# Recursively call for left and right children
return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)
比较绝的是直接把左空或右空或左右都不空的情况合并成一种情况一起处理了。不 zoom out一个 level 很难想到。还是要多练习。靠经验才能有 sense。
时隔一年重新开始刷。这次不能再放下了。一天一题。慢慢来,比较快:)