True
if there exists a root-to-leaf path such that the sum of the node values equals the target sum, otherwise False
.None
, return False
(we’ve reached beyond a leaf without success).True
.## Code Implementation
# 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: TreeNode, target_sum: int) -> bool:
# Helper function to perform the DFS
def dfs(node: TreeNode, current_sum: int) -> bool:
if not node:
return False
current_sum -= node.val
if not node.left and not node.right: # if it's a leaf node
return current_sum == 0
return dfs(node.left, current_sum) or dfs(node.right, current_sum)
return dfs(root, target_sum)
Would you like to proceed with this implementation or have any other questions?
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?