Two Sum IV - Input is a BST

Updated on 07 July, 2025
Two Sum IV - Input is a BST header image

Problem Statement

The problem requires you to find whether there are two distinct nodes in a given binary search tree (BST) such that their values sum up to a specific target integer k. If such a pair exists, the function should return true, otherwise false. A BST is a tree structure where each node has up to two children, and it follows the properties where every node in the left subtree of a node has a value less than or equal to the node’s value, and every node in the right subtree has a value greater than the node’s value. This natural order property influences how we can efficiently search and manage data within the tree.

Examples

Example 1

Input:

root = [5,3,6,2,4,null,7], k = 9

Output:

true

Example 2

Input:

root = [5,3,6,2,4,null,7], k = 28

Output:

false

Constraints

  • The number of nodes in the tree is in the range [1, 104].
  • -104 <= Node.val <= 104
  • root is guaranteed to be a valid binary search tree.
  • -105 <= k <= 105

Approach and Intuition

To solve this problem efficiently given the constraints and property of BST, we can consider the following approach:

  1. Since the elements are arranged in a specific order (due to the BST properties), we can efficiently search for a required compliment of a current node value that sums to k.
  2. A practical and simple approach is to use an auxiliary data structure, such as a set, to keep track of the visited nodes while traversing the tree. This allows checking in constant time whether the complement k - current_node_value exists in the set.
  3. Alternatively, given the sorted nature of BST when In-Order traversed, another effective way is to use two pointers approach similar to the two-sum problem on a sorted array:
    • Convert the BST to a sorted list by in-order traversal.
    • Use two pointers, one starting from the beginning (left_pointer) and the other from the end (right_pointer) of the sorted list.
    • Based on the sum of the values at these two pointers, decide to move the left_pointer to the right or the right_pointer to the left.
  4. The search operation can be stopped as soon as the two pointers cross each other. If a pair is found before the pointers cross, return true, otherwise false.

The first approach offers the ability to maintain the traversal without needing extra space proportional to the number of elements in the BST (outside the set used for look-up). The second approach, while requiring linear space to store the sorted list, offers straightforward and intuitive operations based on the properties of a sorted sequence. Each approach adheres to the constraints provided and leverages the BST properties to ensure efficient performance.

Solutions

  • Java
java
public class Solution {
    public boolean checkIfSumExists(TreeNode node, int target) {
        List<Integer> elements = new ArrayList<>();
        traverseInOrder(node, elements);
        int left = 0, right = elements.size() - 1;
        while (left < right) {
            int currentSum = elements.get(left) + elements.get(right);
            if (currentSum == target)
                return true;
            if (currentSum < target)
                left++;
            else
                right--;
        }
        return false;
    }
    public void traverseInOrder(TreeNode node, List<Integer> elements) {
        if (node == null)
            return;
        traverseInOrder(node.left, elements);
        elements.add(node.val);
        traverseInOrder(node.right, elements);
    }
}

This Java solution addresses the problem of finding two elements in a Binary Search Tree (BST) that sum up to a given target value. The implementation involves two primary functions within the Solution class.

  • checkIfSumExists(TreeNode node, int target):

    • Initialize an empty list elements to hold the node values.
    • Call traverseInOrder to perform an in-order traversal of the BST and populate elements.
    • Use two pointers, left and right, initialized at the start and end of the list respectively, to find two numbers that add up to the target.
    • Loop through elements using the two pointers:
      • Calculate the sum of the elements at the two pointers.
      • If the sum equals the target, return true.
      • If the sum is less than the target, move the left pointer to the right to increase the sum.
      • If the sum is greater than the target, move the right pointer to the left to decrease the sum.
    • Return false if no such pair is found.
  • traverseInOrder(TreeNode node, List<Integer> elements):

    • Recursively traverse the BST in an in-order manner (left node, current node, right node).
    • This order ensures that the elements list is sorted, as BST properties dictate that left children are less than the parent node and right children are greater.
    • Add the node value to elements list during traversal.

The usage of in-order traversal and two-pointer technique makes this approach efficient by leveraging the properties of BST and sorted arrays respectively. This method avoids the need for a nested loop, reducing potential complexity.

Comments

No comments yet.