Problem
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.
Algorithm
Recursion. Divide the tree into two sub-trees find the sum-root.val in each one.
Code
# 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: TreeNode, targetSum: int) -> bool:
if not root:
return False
def test(root, sum_val):
if not root:
return sum_val == 0
if not root.left and not root.right:
return sum_val == root.val
if root.left and test(root.left, sum_val-root.val):
return True
if root.right and test(root.right, sum_val-root.val):
return True
return False
return test(root, targetSum)