Post

Created by @oliverrichards
 at November 28th 2023, 8:22:32 pm.

Technical Interview Question:

Given a binary tree and a target sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

class TreeNode:
    def __init__(self, value=0, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

def has_path_sum(root, target_sum):
    if not root:
        return False
    if not root.left and not root.right and root.value == target_sum:
        return True
    return has_path_sum(root.left, target_sum - root.value) or has_path_sum(root.right, target_sum - root.value)

Explanation:

We can solve this problem using a recursive approach and depth-first search (DFS). The has_path_sum function takes the root of the binary tree and the target_sum as input.

  1. If the root is None, it means the tree is empty, so we return False.

  2. If we reach a leaf node (i.e., a node with no children), we check if the remaining target_sum is equal to the current node's value. If it is, that means we have found a path from the root to a leaf node with the given sum, so we return True.

  3. Otherwise, we recursively call the has_path_sum function for the left and right child nodes, subtracting the current node's value from the target_sum. We perform an OR operation between the results of the left and right subtrees, as we want to find a path in either subtree that satisfies the given sum.

  4. If any of the recursive function calls returns True, it means we have found a path with the given sum, so we return True. Otherwise, we return False.

This approach has a time complexity of O(n), where n is the number of nodes in the binary tree, as we have to visit each node once. The space complexity is also O(n) due to the recursive calls on the call stack.