Given a Balanced Binary Search Tree and a target sum, the task is to check if there exist a pair in BST with sum equal to the target sum. Any modification to the Binary Search Tree is not allowed.
Input:
Output: True Explanation: The node with values 15 and 20 form a pair which sum up to give target.
[Naive Approach] Check Compliment for Every node - O(n * h) Time and O(h) Space
The idea is to traverse the BST and for each node and search for their compliment , that is (target - node value) in the BST. If the complement is found, return true. Otherwise, continue checking the left and right subtrees recursively. If no such pair is found by the end of traversal, return false.
Below is the implementation of the above approach:
C++
//Driver Code Starts// C++ code to find a pair with given sum// in a Balanced BST#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intd){data=d;left=nullptr;right=nullptr;}};//Driver Code Ends// Function to search for the Key in the BSTboolsearch(Node*root,intkey,Node*temp){// If the root is NULL, return falseif(root==nullptr)returnfalse;// Start search from the rootNode*current=root;// Traverse the BST to find the target value `k`while(current!=nullptr){// If Key is foundif(current->data==key&¤t!=temp)returntrue;// If key is smaller, move to the leftelseif(key<current->data)current=current->left;// If key is larger, move to the rightelsecurrent=current->right;}// Return false if no match is foundreturnfalse;}// Helper Function to find if there exists a pair // with a given sum in the BSTboolfindTargetRec(Node*root,Node*current,inttarget){if(current==nullptr)returnfalse;// Check if the complement of the current node value existsintcomplement=target-current->data;if(search(root,complement,current))returntrue;// Check for the pair in left and right subtreereturnfindTargetRec(root,current->left,target)||findTargetRec(root,current->right,target);}// Function to find if there exists a pair // with a given sum in the BSTboolfindTarget(Node*root,inttarget){returnfindTargetRec(root,root,target);}//Driver Code Startsintmain(){// BST structure//// 15// / \ // 10 20// / \ / \ // 8 12 16 25Node*root=newNode(15);root->left=newNode(10);root->right=newNode(20);root->left->left=newNode(8);root->left->right=newNode(12);root->right->left=newNode(16);root->right->right=newNode(25);inttarget=35;cout<<(findTarget(root,target)?"True":"False");return0;}//Driver Code Ends
C
//Driver Code Starts// C code to find a pair with given sum// in a Balanced BST#include<stdio.h>#include<stdlib.h>#include<stdbool.h>typedefstructNode{intdata;structNode*left;structNode*right;}Node;// Function to create a new nodeNode*newNode(intd){Node*node=(Node*)malloc(sizeof(Node));node->data=d;node->left=node->right=NULL;returnnode;}//Driver Code Ends// Function to search for the Key in the BSTboolsearch(Node*root,intkey,Node*temp){// If the root is NULL, return falseif(root==NULL)returnfalse;// Start search from the rootNode*current=root;// Traverse the BST to find the target value `key`while(current!=NULL){// If Key is foundif(current->data==key&¤t!=temp)returntrue;// If key is smaller, move to the leftelseif(key<current->data)current=current->left;// If key is larger, move to the rightelsecurrent=current->right;}// Return false if no match is foundreturnfalse;}// Helper Function to find if there exists a pair // with a given sum in the BSTboolfindTargetRec(Node*root,Node*current,inttarget){if(current==NULL)returnfalse;// Check if the complement of the current node value existsintcomplement=target-current->data;if(search(root,complement,current))returntrue;// Check for the pair in left and right subtreereturnfindTargetRec(root,current->left,target)||findTargetRec(root,current->right,target);}// Function to find if there exists a pair // with a given sum in the BSTboolfindTarget(Node*root,inttarget){returnfindTargetRec(root,root,target);}//Driver Code Startsintmain(){// BST structure//// 15// / \ // 10 20// / \ / \ // 8 12 16 25Node*root=newNode(15);root->left=newNode(10);root->right=newNode(20);root->left->left=newNode(8);root->left->right=newNode(12);root->right->left=newNode(16);root->right->right=newNode(25);inttarget=35;// Print resultprintf("%s",findTarget(root,target)?"True":"False");return0;}//Driver Code Ends
Java
//Driver Code Starts// Java program to find a pair with given sum// in a Balanced BSTclassNode{intdata;Nodeleft,right;Node(intd){data=d;left=right=null;}}classGfG{//Driver Code Ends// Function to search for the Key in the BSTstaticbooleansearch(Noderoot,intkey,Nodetemp){// If the root is NULL, return falseif(root==null)returnfalse;// Start search from the rootNodecurrent=root;// Traverse the BST to find the target value `key`while(current!=null){// If Key is foundif(current.data==key&¤t!=temp)returntrue;// If key is smaller, move to the leftelseif(key<current.data)current=current.left;// If key is larger, move to the rightelsecurrent=current.right;}// Return false if no match is foundreturnfalse;}// Helper Function to find if there exists a pair // with a given sum in the BSTstaticbooleanfindTargetRec(Noderoot,Nodecurrent,inttarget){if(current==null)returnfalse;// Check if the complement of the current node value existsintcomplement=target-current.data;if(search(root,complement,current))returntrue;// Check for the pair in left and right subtreereturnfindTargetRec(root,current.left,target)||findTargetRec(root,current.right,target);}// Function to find if there exists a pair // with a given sum in the BSTstaticbooleanfindTarget(Noderoot,inttarget){returnfindTargetRec(root,root,target);}//Driver Code Startspublicstaticvoidmain(String[]args){// BST structure//// 15// / \// 10 20// / \ / \// 8 12 16 25Noderoot=newNode(15);root.left=newNode(10);root.right=newNode(20);root.left.left=newNode(8);root.left.right=newNode(12);root.right.left=newNode(16);root.right.right=newNode(25);inttarget=35;// Print resultSystem.out.println(findTarget(root,target)?"True":"False");}}//Driver Code Ends
Python
#Driver Code Starts# Python program to find a pair with given sum# in a Balanced BSTclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None#Driver Code Ends# Function to search for the Key in the BSTdefsearch(root,key,temp):# If the root is NULL, return falseifrootisNone:returnFalse# Start search from the rootcurrent=root# Traverse the BST to find the target value `key`whilecurrent:# If Key is foundifcurrent.data==keyandcurrent!=temp:returnTrue# If key is smaller, move to the leftelifkey<current.data:current=current.left# If key is larger, move to the rightelse:current=current.right# Return false if no match is foundreturnFalse# Helper Function to find if there exists a pair # with a given sum in the BSTdeffindTargetRec(root,current,target):ifcurrentisNone:returnFalse# Check if the complement of the current node value existscomplement=target-current.dataifsearch(root,complement,current):returnTrue# Check for the pair in left and right subtreereturnfindTargetRec(root,current.left,target)or \
findTargetRec(root,current.right,target)# Function to find if there exists a pair # with a given sum in the BSTdeffindTarget(root,target):returnfindTargetRec(root,root,target)#Driver Code Startsif__name__=="__main__":# BST structure## 15# / \# 10 20# / \ / \# 8 12 16 25root=Node(15)root.left=Node(10)root.right=Node(20)root.left.left=Node(8)root.left.right=Node(12)root.right.left=Node(16)root.right.right=Node(25)target=35print("True"iffindTarget(root,target)else"False")#Driver Code Ends
C#
//Driver Code Starts// C# program to find a pair with given sum// in a Balanced BSTusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intd){data=d;left=right=null;}}classGfG{//Driver Code Ends// Function to search for the Key in the BSTstaticboolSearch(Noderoot,intkey,Nodetemp){// If the root is NULL, return falseif(root==null)returnfalse;// Start search from the rootNodecurrent=root;// Traverse the BST to find the target value `key`while(current!=null){// If Key is foundif(current.data==key&¤t!=temp)returntrue;// If key is smaller, move to the leftelseif(key<current.data)current=current.left;// If key is larger, move to the rightelsecurrent=current.right;}// Return false if no match is foundreturnfalse;}// Helper Function to find if there exists a pair // with a given sum in the BSTstaticboolFindTargetRec(Noderoot,Nodecurrent,inttarget){if(current==null)returnfalse;// Check if the complement of the current node value existsintcomplement=target-current.data;if(Search(root,complement,current))returntrue;// Check for the pair in left and right subtreereturnFindTargetRec(root,current.left,target)||FindTargetRec(root,current.right,target);}// Function to find if there exists a pair // with a given sum in the BSTstaticboolFindTarget(Noderoot,inttarget){returnFindTargetRec(root,root,target);}//Driver Code StartsstaticvoidMain(string[]args){// BST structure//// 15// / \// 10 20// / \ / \// 8 12 16 25Noderoot=newNode(15);root.left=newNode(10);root.right=newNode(20);root.left.left=newNode(8);root.left.right=newNode(12);root.right.left=newNode(16);root.right.right=newNode(25);inttarget=35;Console.WriteLine(FindTarget(root,target)?"True":"False");}}//Driver Code Ends
JavaScript
//Driver Code Starts// JavaScript program to find a pair with given sum// in a Balanced BSTclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}//Driver Code Ends// Function to search for the Key in the BSTfunctionsearch(root,key,temp){// If the root is NULL, return falseif(root===null)returnfalse;// Start search from the rootletcurrent=root;// Traverse the BST to find the target value `key`while(current!==null){// If Key is foundif(current.data===key&¤t!==temp)returntrue;// If key is smaller, move to the leftelseif(key<current.data)current=current.left;// If key is larger, move to the rightelsecurrent=current.right;}// Return false if no match is foundreturnfalse;}// Helper Function to find if there exists a pair // with a given sum in the BSTfunctionfindTargetRec(root,current,target){if(current===null)returnfalse;// Check if the complement of the current node value existsconstcomplement=target-current.data;if(search(root,complement,current))returntrue;// Check for the pair in left and right subtreereturnfindTargetRec(root,current.left,target)||findTargetRec(root,current.right,target);}// Function to find if there exists a pair // with a given sum in the BSTfunctionfindTarget(root,target){returnfindTargetRec(root,root,target);}//Driver Code Starts// Driver Code// BST structure//// 15// / \// 10 20// / \ / \// 8 12 16 25constroot=newNode(15);root.left=newNode(10);root.right=newNode(20);root.left.left=newNode(8);root.left.right=newNode(12);root.right.left=newNode(16);root.right.right=newNode(25);consttarget=35;console.log(findTarget(root,target)?"True":"False");//Driver Code Ends
Output
True
[Expected approach] Using Inorder Traversal - O(n) Time and O(n) Space
The idea is to create an auxiliary array and store the Inorder traversal of BST in the array. The array will be sorted as Inorder traversal of BST always produces sorted data. Now we can apply Two pointer technique to find the pair of integers with sum equal to target. (Refer Two sum for details).
C++
//Driver Code Starts// C++ code to find a pair with given sum in a Balanced BST// Using Inorder Traversal#include<iostream>#include<vector>usingnamespacestd;structNode{intdata;Node*left;Node*right;Node(intd){data=d;left=nullptr;right=nullptr;}};//Driver Code Ends// Function to perform Inorder traversal and store the // elements in a vectorvoidinorderTraversal(Node*root,vector<int>&inorder){if(root==nullptr)return;inorderTraversal(root->left,inorder);// Store the current node's valueinorder.push_back(root->data);inorderTraversal(root->right,inorder);}// Function to find if there exists a pair with a // given sum in the BSTboolfindTarget(Node*root,inttarget){// Create an auxiliary array and store Inorder traversalvector<int>inorder;inorderTraversal(root,inorder);// Use two-pointer technique to find the pair with given sumintleft=0,right=inorder.size()-1;while(left<right){intcurrentSum=inorder[left]+inorder[right];// If the pair is found, return trueif(currentSum==target)returntrue;// If the current sum is less than the target, // move the left pointerif(currentSum<target)left++;// If the current sum is greater than // the target, move the right pointerelseright--;}returnfalse;}//Driver Code Startsintmain(){// BST structure//// 15// / \ // 10 20// / \ / \ // 8 12 16 25Node*root=newNode(15);root->left=newNode(10);root->right=newNode(20);root->left->left=newNode(8);root->left->right=newNode(12);root->right->left=newNode(16);root->right->right=newNode(25);inttarget=35;cout<<(findTarget(root,target)?"True":"False");return0;}//Driver Code Ends
Java
//Driver Code Starts// Java program to find a pair with given sum in a Balanced BST// Using Inorder Traversalimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intdata){this.data=data;left=null;right=null;}}classGfG{//Driver Code Ends// Function to perform Inorder traversal and store the // elements in an arraystaticvoidinorderTraversal(Noderoot,ArrayList<Integer>inorder){if(root==null)return;inorderTraversal(root.left,inorder);// Store the current node's valueinorder.add(root.data);inorderTraversal(root.right,inorder);}// Function to find if there exists a pair with a // given sum in the BSTstaticbooleanfindTarget(Noderoot,inttarget){// Create an auxiliary array and store Inorder traversalArrayList<Integer>inorder=newArrayList<>();inorderTraversal(root,inorder);// Use two-pointer technique to find the pair with given sumintleft=0,right=inorder.size()-1;while(left<right){intcurrentSum=inorder.get(left)+inorder.get(right);// If the pair is found, return trueif(currentSum==target)returntrue;// If the current sum is less than the target, // move the left pointerif(currentSum<target)left++;// If the current sum is greater than // the target, move the right pointerelseright--;}returnfalse;}//Driver Code Startspublicstaticvoidmain(String[]args){// BST structure//// 15// / \// 10 20// / \ / \// 8 12 16 25Noderoot=newNode(15);root.left=newNode(10);root.right=newNode(20);root.left.left=newNode(8);root.left.right=newNode(12);root.right.left=newNode(16);root.right.right=newNode(25);inttarget=35;System.out.println(findTarget(root,target)?"True":"False");}}//Driver Code Ends
Python
#Driver Code Starts# Python program to find a pair with given sum in a Balanced BST# Using Inorder TraversalclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None#Driver Code Ends# Function to perform Inorder traversal and store the # elements in an arraydefinorderTraversal(root,inorder):ifrootisNone:returninorderTraversal(root.left,inorder)# Store the current node's valueinorder.append(root.data)inorderTraversal(root.right,inorder)# Function to find if there exists a pair with a # given sum in the BSTdeffindTarget(root,target):# Create an auxiliary array and store Inorder traversalinorder=[]inorderTraversal(root,inorder)# Use two-pointer technique to find the pair with given sumleft,right=0,len(inorder)-1whileleft<right:currentSum=inorder[left]+inorder[right]# If the pair is found, return trueifcurrentSum==target:returnTrue# If the current sum is less than the target, # move the left pointerifcurrentSum<target:left+=1# If the current sum is greater than # the target, move the right pointerelse:right-=1returnFalse#Driver Code Startsif__name__=="__main__":# BST structure## 15# / \# 10 20# / \ / \# 8 12 16 25root=Node(15)root.left=Node(10)root.right=Node(20)root.left.left=Node(8)root.left.right=Node(12)root.right.left=Node(16)root.right.right=Node(25)target=35print("True"iffindTarget(root,target)else"False")#Driver Code Ends
C#
//Driver Code Starts// C# program to find a pair with given sum in a Balanced BST// Using Inorder TraversalusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intdata){this.data=data;left=right=null;}}classGfG{//Driver Code Ends// Function to perform Inorder traversal and store the // elements in a liststaticvoidInorderTraversal(Noderoot,List<int>inorder){if(root==null)return;InorderTraversal(root.left,inorder);// Store the current node's valueinorder.Add(root.data);InorderTraversal(root.right,inorder);}// Function to find if there exists a pair with a // given sum in the BSTstaticboolFindTarget(Noderoot,inttarget){// Create an auxiliary list and store Inorder traversalList<int>inorder=newList<int>();InorderTraversal(root,inorder);// Use two-pointer technique to find the pair with given sumintleft=0,right=inorder.Count-1;while(left<right){intcurrentSum=inorder[left]+inorder[right];// If the pair is found, return trueif(currentSum==target)returntrue;// If the current sum is less than the target, // move the left pointerif(currentSum<target)left++;// If the current sum is greater than // the target, move the right pointerelseright--;}returnfalse;}//Driver Code StartsstaticvoidMain(string[]args){// BST structure//// 15// / \// 10 20// / \ / \// 8 12 16 25Noderoot=newNode(15);root.left=newNode(10);root.right=newNode(20);root.left.left=newNode(8);root.left.right=newNode(12);root.right.left=newNode(16);root.right.right=newNode(25);inttarget=35;Console.WriteLine(FindTarget(root,target)?"True":"False");}}//Driver Code Ends
JavaScript
//Driver Code Starts// JavaScript program to find a pair with given sum in a Balanced BST// Using Inorder TraversalclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}//Driver Code Ends// Function to perform Inorder traversal and store the // elements in an arrayfunctioninorderTraversal(root,inorder){if(root===null)return;inorderTraversal(root.left,inorder);// Store the current node's valueinorder.push(root.data);inorderTraversal(root.right,inorder);}// Function to find if there exists a pair with a // given sum in the BSTfunctionfindTarget(root,target){// Create an auxiliary array and store Inorder traversalletinorder=[];inorderTraversal(root,inorder);// Use two-pointer technique to find the pair with given sumletleft=0,right=inorder.length-1;while(left<right){letcurrentSum=inorder[left]+inorder[right];// If the pair is found, return trueif(currentSum===target)returntrue;// If the current sum is less than the target, // move the left pointerif(currentSum<target)left++;// If the current sum is greater than // the target, move the right pointerelseright--;}returnfalse;}//Driver Code Starts// Driver Code// BST structure//// 15// / \// 10 20// / \ / \// 8 12 16 25constroot=newNode(15);root.left=newNode(10);root.right=newNode(20);root.left.left=newNode(8);root.left.right=newNode(12);root.right.left=newNode(16);root.right.right=newNode(25);consttarget=35;console.log(findTarget(root,target)?"True":"False");//Driver Code Ends