KatInterview

653. Two Sum IV - Input is a BST

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine if there exist two nodes in a given Binary Search Tree (BST) whose values sum up to a target integer k. This is a classic "Two Sum" problem applied to a BST data structure.

Solution

Two Sum IV - Input is a BST in Python

# 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
class Solution:
    def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
        # We use a set `seen` to store the values of nodes we have visited.
        seen = set()
        
        # We define a helper function to traverse the tree using DFS.
        def dfs(node: Optional[TreeNode]) -> bool:
            # Base case: if the node is None, we've reached the end of a path.
            if not node:
                return False
            
            # Calculate the complement needed for the current node's value.
            complement = k - node.val
            
            # If the complement exists in our `seen` set, we have found a pair.
            if complement in seen:
                return True
            
            # Otherwise, add the current node's value to the `seen` set.
            seen.add(node.val)
            
            # Recursively search in the left and right subtrees.
            # The `or` operator provides short-circuiting: if a pair is found
            # in the left subtree, the right subtree won't be searched.
            return dfs(node.left) or dfs(node.right)
        
        return dfs(root)

Two Sum IV - Input is a BST in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
import java.util.HashSet;
import java.util.Set;

class Solution {
    public boolean findTarget(TreeNode root, int k) {
        // Use a HashSet to store the values of nodes we've seen so far.
        Set<Integer> seen = new HashSet<>();
        // Start the DFS traversal from the root.
        return dfs(root, k, seen);
    }

    private boolean dfs(TreeNode node, int k, Set<Integer> seen) {
        // Base case: if the node is null, we've reached the end of a branch.
        if (node == null) {
            return false;
        }

        // Calculate the complement needed to reach the target k.
        int complement = k - node.val;

        // If the complement is found in the HashSet, we've found a pair.
        if (seen.contains(complement)) {
            return true;
        }

        // If the complement is not found, add the current node's value to the set.
        seen.add(node.val);

        // Recursively call dfs on the left and right children.
        // The || operator ensures that if the left subtree finds a pair, 
        // the right subtree is not explored (short-circuiting).
        return dfs(node.left, k, seen) || dfs(node.right, k, seen);
    }
}

Two Sum IV - Input is a BST in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <unordered_set>

class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        std::unordered_set<int> seen;
        return dfs(root, k, seen);
    }

private:
    // Helper function to perform DFS traversal.
    bool dfs(TreeNode* node, int k, std::unordered_set<int>& seen) {
        // Base case: if the node is null, we can't find a value here.
        if (!node) {
            return false;
        }

        // Calculate the complement for the current node's value.
        int complement = k - node->val;

        // Check if the complement exists in the set of seen values.
        // The count function returns 1 if the element is found, 0 otherwise.
        if (seen.count(complement)) {
            return true;
        }

        // If complement is not found, add the current node's value to the set.
        seen.insert(node->val);

        // Recursively search in the left and right subtrees.
        // If a pair is found in either subtree, the '||' operator will short-circuit
        // and return true immediately.
        return dfs(node->left, k, seen) || dfs(node->right, k, seen);
    }
};

Two Sum IV - Input is a BST in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findTarget(root: TreeNode | null, k: number): boolean {
    // The solution uses a HashSet (`Set` in JS/TS) to keep track of visited node values.
    const seen = new Set<number>();
    
    // A recursive Depth-First Search (DFS) function `dfs` traverses the tree.
    function dfs(node: TreeNode | null): boolean {
        // Base case: if the node is null, we've reached the end of a branch.
        if (!node) {
            return false;
        }
        
        // Calculate the complement needed for the current node's value.
        const complement = k - node.val;
        
        // If the complement exists in the set, a pair is found.
        if (seen.has(complement)) {
            return true;
        }
        
        // Otherwise, the current node's value is added to the set.
        seen.add(node.val);
        
        // Recursively search in the left and right subtrees.
        // The `||` operator provides a short-circuit mechanism: if the left subtree search
        // returns true, the right subtree search is skipped.
        return dfs(node.left) || dfs(node.right);
    }
    
    return dfs(root);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.