Find a Pair with a Given Sum in BST using JavaScript
Last Updated :
29 Apr, 2024
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]
BSTBelow 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]
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]
Time complexity: O(n)
Space complexity: O(h) where h is the height of the tree
Similar Reads
Search a Given Key in BST using JavaScript Given a binary search tree and a key, determine if the key is present in the tree. If the key is present, return the node containing the key otherwise, return null. Example: Input : {15,20,10,8,12,16,25}, Key : 20Output : 20 found 15 / \ 10 20 / \ / \ 8 12 16 25Table of Content Recursive ApproachIte
3 min read
Check if Pair with Given Sum Exists in Array in JavaScript Two Sum is a classic algorithmic problem where you're given an array of integers and a target sum. The task is to determine whether any two numbers in the array add up to the target sum. Given an array A[] of n numbers and another number x, the task is to check whether or not there exist two element
3 min read
Sum of Distinct Elements of an Array using JavaScript One can find a Sum of distinct elements (unique or different numbers) present in an array using JavaScript. Below is an example to understand the problem clearly. Example:Input: [ 1,2, 3, 1, 3, 4, 5, 5, 2] Output: 15 Explanation: The distinct elements present in array are: 1, 2, 3, 4 and 5 Sum = 1 +
4 min read
JavaScript Program to Find the Sum of Elements Between Two Given Indices in an Array In JavaScript programming, there are often scenarios where we need to calculate the sum of elements within a specific range in an array. This can be useful in various applications, such as calculating subarray sums in algorithms or performing range-based calculations in data analysis. Example: Input
3 min read
Finding Sum of Alternate Elements of the Array using JavaScript Given an array, our task is to find the sum of alternative elements of the array using JavaScript. Example: Input: array = { 1, 2, 3, 4, 5, 6, 7, 8}Output: 16 Explanation:Sum of alternate elements of array = 1 + 3 + 5 + 7 = 16 Table of Content Using a for-loopUsing reduce Method Using Filter and Red
3 min read
Sum of all subsets in array using JavaScript We are given an array, we have to print the sum of the subset generated. If the number of elements in the array is n, then 2n subset will be generated. One empty subset will also be generated. So the total subset generated is (2n + 1). Example: Input: 1 , 2, 3 Output: 0 , 1 , 2 , 3 , 3 , 4 , 5 , 6Ex
3 min read