Open In App

Find a Pair with a Given Sum in BST using JavaScript

Last Updated : 29 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a target sum and Binary Search Tree (BST), we have to write a function to find out the pair of nodes in BST whose values will sum up to this given sum. We must give these two numbers as an array that adds up to get this target sum. If there is no such number pair, return null.

Example:

Input: sum = 28, given BST
Output: [1,8]
b-n

BST

Below are the approaches to find a pair with a given sum in BST using JavaScript:

Inorder Traversal and Two-Pointer Technique

Inorder traversal of BST gives elements in sorted order. We are going to traverse the BST in inorder manner and keep storing every element inside an array. When we obtain an ordered arrangement from the inorder traversal then we employ two pointer technique to identify pairs whose summation results into target sum by taking one pointer at beginning of array and another at end or rightmost position.

Example: This example shows the use of the above-explained approach.

JavaScript
class TreeNode {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

function findPairWithSumInBST(root, sum) {
    // Inorder traversal to convert BST to a sorted array
    function inorderTraversal(node, arr) {
        if (!node) return;
        inorderTraversal(node.left, arr);
        arr.push(node.val);
        inorderTraversal(node.right, arr);
    }
    
    const arr = [];
    inorderTraversal(root, arr);
    
    // Two-pointer technique
    let left = 0;
    let right = arr.length - 1;
    while (left < right) {
        const currentSum = arr[left] + arr[right];
        if (currentSum === sum) {
            return [arr[left], arr[right]]; // Pair found
        } else if (currentSum < sum) {
            left++;
        } else {
            right--;
        }
    }
    return null; // No pair found
}

// Example usage
const root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(8);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(7);
root.right.right = new TreeNode(10);

const sum = 9;
const pair = findPairWithSumInBST(root, sum);
console.log(pair); // Output: [1, 8]

Output
[ 1, 8 ]

Time complexity: O(n)

Space complexity: O(n)

Iterative Two-Pointer Approach Using BST Iterators

We have two iterators — one for the smallest (leftmost) element and another for the largest (rightmost) element in BST which traverse the BST in an inorder(left to right) and reverse(right to left) order.

We initialize the iterators to be the smallest and biggest values in the BST, then we employ a two-pointer technique that causes them to move closer together while comparing sums of the values at their positions. In case, such sum is equal to target sum, this means we have found a pair.

Example: This example shows the use of the above-explained approach.

JavaScript
class TreeNode {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

class BSTIterator {
    constructor(root, forward = true) {
        this.stack = [];
        
        // true for inorder (left to right), false for reverse (right to left)
        this.forward = forward; 
        this.pushAll(root);
    }

    pushAll(node) {
        while (node) {
            this.stack.push(node);
            node = this.forward ? node.left : node.right;
        }
    }

    hasNext() {
        return this.stack.length > 0;
    }

    next() {
        const node = this.stack.pop();
        if (this.forward) {
            this.pushAll(node.right);
        } else {
            this.pushAll(node.left);
        }
        return node.val;
    }
}

function findPairWithSumInBST(root, sum) {
    // Initialize left and right iterators
    
    // left to right (inorder)
    const leftIterator = new BSTIterator(root, true); 
    
    // right to left (reverse)
    const rightIterator = new BSTIterator(root, false); 
    
    // Retrieve the initial values from the iterators
    let left = leftIterator.next();
    let right = rightIterator.next();
    
    // Use the two-pointer technique to find the pair 
    // with the given sum
    while (left < right) {
        const currentSum = left + right;
        if (currentSum === sum) {
            return [left, right]; // Pair found
        } else if (currentSum < sum) {
            // Move the left pointer forward
            left = leftIterator.next();
        } else {
            // Move the right pointer backward
            right = rightIterator.next();
        }
    }
    return null; // No pair found
}

// Example usage
const root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(8);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(7);
root.right.right = new TreeNode(10);

const sum = 9;
const pair = findPairWithSumInBST(root, sum);
console.log(pair); // Output: [1, 8]

Output
[ 1, 8 ]

Time complexity: O(n)

Space complexity: O(h) where h is the height of the tree



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads