Day 16: Path Sum (Tree Depth First Search)
Recommended: Solution
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.
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1]
targetSum = 22
Output: true
# 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
def hasPathSum(root, targetSum):
if not root:
return False
if not root.left and not root.right:
return targetSum == root.val
return hasPathSum(root.left, targetSum - root.val) or hasPathSum(root.right, targetSum
Data Analyst | Public Health & Patient Support Specialist Enhancing Healthcare Outcomes with Data-Driven Insights | Customer Analytics & Predictive Insights | Machine Learning for Business Growth |
6 个月Great tips. Keep it up ??