Hone logo
Hone
Problems

Binary Tree Path Sum

You are tasked with determining if a given binary tree contains a root-to-leaf path whose node values sum up to a specific target value. This is a common problem in tree manipulation and can be useful for various applications, such as validating data structures or implementing search algorithms within hierarchical data.

Problem Description

Given the root of a binary tree and an integer targetSum, determine if there exists a root-to-leaf path such that the sum of all the node values along the path equals targetSum.

A leaf is a node with no children. A root-to-leaf path is a sequence of nodes starting from the root and ending at any leaf node.

Key Requirements:

  • Traverse the binary tree to find all root-to-leaf paths.
  • For each path, calculate the sum of its node values.
  • Compare the calculated sum with the targetSum.
  • Return true if at least one such path is found, false otherwise.

Expected Behavior:

  • The function should return a boolean value.
  • If the tree is empty, it should be handled appropriately.

Edge Cases to Consider:

  • An empty tree.
  • A tree with only a root node.
  • A tree where the targetSum can only be achieved by a path that includes negative numbers.

Examples

Example 1:

Input:
    root = [5,4,8,11,null,13,4,7,2,null,null,null,1]
    targetSum = 22

    Visual Representation:
          5
         / \
        4   8
       /   / \
      11  13  4
     /  \      \
    7    2      1

Output: true
Explanation: The root-to-leaf path 5 -> 4 -> 11 -> 2 sums to 22. (5 + 4 + 11 + 2 = 22)

Example 2:

Input:
    root = [1,2,3]
    targetSum = 5

    Visual Representation:
          1
         / \
        2   3

Output: false
Explanation: There is no root-to-leaf path that sums to 5.
    Path 1 -> 2 sums to 3.
    Path 1 -> 3 sums to 4.

Example 3:

Input:
    root = []
    targetSum = 0

Output: false
Explanation: An empty tree has no paths, so no path can sum to the target.

Constraints

  • The number of nodes in the tree is in the range [0, 5000].
  • The value of each node is in the range [-1000, 1000].
  • The targetSum is in the range [-100000, 100000].

Notes

  • You will likely need a recursive approach or an iterative approach using a stack to explore all possible paths.
  • Be mindful of how you keep track of the current sum as you traverse down the tree.
  • A node is considered a leaf if it has no left child AND no right child.
  • Consider the case where the targetSum itself is negative.
Loading editor...
plaintext