Post

Created by @oliverrichards
 at December 10th 2023, 8:13:25 pm.

Technical Interview Question:

You are given a binary search tree (BST) and two integers, low and high. Your task is to find the sum of all node values in the BST within the range [low, high].

Write a function rangeSumBST to accomplish this task. The function should take a binary search tree and two integers low and high as input and return the sum of node values within the given range.

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

def rangeSumBST(root, low, high):
    # Implementation of the function goes here
    pass

Example: Given the following binary search tree:

       10
      /  \
     5   15
    / \    \
   3   7   18

The range sum for low = 7 and high = 15 would be 7 + 10 + 15 = 32.

Provide the implementation of the rangeSumBST function in Python with a step-by-step detailed explanation.

def rangeSumBST(root, low, high):
    # Base case: If the tree is empty, return 0
    if root is None:
        return 0
    
    # If the current node value is within the range, add it to the sum
    if low <= root.val <= high:
        return (root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high))
    
    # If the current node value is less than low, search only the right subtree
    elif root.val < low:
        return rangeSumBST(root.right, low, high)
    
    # If the current node value is greater than high, search only the left subtree
    else:
        return rangeSumBST(root.left, low, high)

Explanation:

  1. We start by defining the rangeSumBST function that takes the root of the binary search tree and the low and high integers as arguments.

  2. In the function, we first handle the base case. If the current node is None (i.e., the tree is empty), we return 0 since there are no nodes to consider.

  3. Next, we check if the value of the current node falls within the range defined by low and high. If it does, we add the current node's value to the sum and recursively call the rangeSumBST function for its left and right subtrees while passing the same low and high values.

  4. If the current node's value is less than low, we know that all the nodes in the left subtree will also be less than low, so we only need to search the right subtree.

  5. If the current node's value is greater than high, we know that all the nodes in the right subtree will also be greater than high, so we only need to search the left subtree.

  6. By following these steps, the function efficiently computes the sum of node values within the given range in the binary search tree.