Given the root of binary search tree (BST) and an integer target, the task is to find if there exist a pair of elements such that their sum is equal to given target.
Example:
Input: target = 12
Output: True Explanation: In the binary tree above, there are two nodes (8 and 4) that add up to 12.
Input: target = 23
Output: False Explanation: In the binary tree above, there are no such two nodes exists that add up to 23.
[Expected Approach 1] Using Hash Set - O(n) time and O(n) space
The idea is that if we know one number in the pair, say x, we only need to check if the other number, target - x, exists in the tree. As we traverse the tree, we can store the values we've encountered in a HashSet. For each node, we check if target - node's value is in the hashset. If it is, we return true. If not, we add the current node's value to the set and continue traversing.
Note: This approach works for binary trees as well.
C++
//Driver Code Starts// C++ code to find a pair with given sum in a Balanced BST// Using Hash Set#include<iostream>#include<unordered_set>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};//Driver Code Ends// Helper function to perform DFS and check// for the required target.booldfs(Node*root,unordered_set<int>&st,inttarget){if(root==nullptr)returnfalse;// Check if the complement (target - current node's value)// exists in the setif(st.find(target-root->data)!=st.end())returntrue;// Insert the current node's value into the setst.insert(root->data);// Continue the search in the left and right subtreesreturndfs(root->left,st,target)||dfs(root->right,st,target);}// Main function to check if two elements// in the BST target to targetboolfindTarget(Node*root,inttarget){// To store visited nodes' valuesunordered_set<int>st;// Start DFS from the rootreturndfs(root,st,target);}//Driver Code Startsintmain(){// Constructing the following BST:// 7// / \ // 3 8// / \ \ // 2 4 9Node*root=newNode(7);root->left=newNode(3);root->right=newNode(8);root->left->left=newNode(2);root->left->right=newNode(4);root->right->right=newNode(9);inttarget=12;// Check if there are two elements in the BST// that added to "target"if(findTarget(root,target))cout<<"True";elsecout<<"False";return0;}//Driver Code Ends
Java
//Driver Code Starts// Java code to find a pair with given sum in a Balanced BST// Using Hash Setimportjava.util.HashSet;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{//Driver Code Ends// Helper function to perform DFS and check// for the required target.staticbooleandfs(Noderoot,HashSet<Integer>set,inttarget){if(root==null)returnfalse;// Check if the complement (target - current node's value)// exists in the setif(set.contains(target-root.data))returntrue;// Insert the current node's value into the setset.add(root.data);// Continue the search in the left and right subtreesreturndfs(root.left,set,target)||dfs(root.right,set,target);}// Main function to check if two elements// in the BST target to targetstaticbooleanfindTarget(Noderoot,inttarget){HashSet<Integer>set=newHashSet<>();returndfs(root,set,target);}//Driver Code Startspublicstaticvoidmain(String[]args){// Constructing the following BST:// 7// / \// 3 8// / \ \// 2 4 9Noderoot=newNode(7);root.left=newNode(3);root.right=newNode(8);root.left.left=newNode(2);root.left.right=newNode(4);root.right.right=newNode(9);inttarget=12;// Check if there are two elements in the BST// that added to "target"if(findTarget(root,target))System.out.println("True");elseSystem.out.println("False");}}//Driver Code Ends
Python
#Driver Code Starts# Python code to find a pair with given sum in a Balanced BST# Using Hash SetclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None#Driver Code Ends# Helper function to perform DFS and check# for the required target.defdfs(root,st,target):ifrootisNone:returnFalse# Check if the complement (target - current node's value)# exists in the setiftarget-root.datainst:returnTrue# Insert the current node's value into the setst.add(root.data)# Continue the search in the left and right subtreesreturndfs(root.left,st,target)ordfs(root.right,st,target)# Main function to check if two elements# in the BST target to targetdeffindTarget(root,target):st=set()returndfs(root,st,target)#Driver Code Startsif__name__=="__main__":# Constructing the following BST:# 7# / \# 3 8# / \ \# 2 4 9root=Node(7)root.left=Node(3)root.right=Node(8)root.left.left=Node(2)root.left.right=Node(4)root.right.right=Node(9)target=12# Check if there are two elements in the BST# that added to "target"iffindTarget(root,target):print("True")else:print("False")#Driver Code Ends
C#
//Driver Code Starts// C# code to find a pair with given sum in a Balanced BST// Using Hash SetusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{//Driver Code Ends// Helper function to perform DFS and check// for the required target.staticbooldfs(Noderoot,HashSet<int>set,inttarget){if(root==null)returnfalse;// Check if the complement (target - current node's value)// exists in the setif(set.Contains(target-root.data))returntrue;// Insert the current node's value into the setset.Add(root.data);// Continue the search in the left and right subtreesreturndfs(root.left,set,target)||dfs(root.right,set,target);}// Main function to check if two elements// in the BST target to targetstaticboolfindTarget(Noderoot,inttarget){HashSet<int>set=newHashSet<int>();returndfs(root,set,target);}//Driver Code StartsstaticvoidMain(string[]args){// Constructing the following BST:// 7// / \// 3 8// / \ \// 2 4 9Noderoot=newNode(7);root.left=newNode(3);root.right=newNode(8);root.left.left=newNode(2);root.left.right=newNode(4);root.right.right=newNode(9);inttarget=12;// Check if there are two elements in the BST// that added to "target"if(findTarget(root,target))Console.WriteLine("True");elseConsole.WriteLine("False");}}//Driver Code Ends
JavaScript
//Driver Code Starts// JavaScript code to find a pair with given sum in a Balanced BST// Using Hash SetclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}//Driver Code Ends// Helper function to perform DFS and check// for the required target.functiondfs(root,set,target){if(root===null)returnfalse;// Check if the complement (target - current node's value)// exists in the setif(set.has(target-root.data))returntrue;// Insert the current node's value into the setset.add(root.data);// Continue the search in the left and right subtreesreturndfs(root.left,set,target)||dfs(root.right,set,target);}// Main function to check if two elements// in the BST target to targetfunctionfindTarget(root,target){constset=newSet();returndfs(root,set,target);}//Driver Code Starts// Driver Code// Constructing the following BST:// 7// / \// 3 8// / \ \// 2 4 9constroot=newNode(7);root.left=newNode(3);root.right=newNode(8);root.left.left=newNode(2);root.left.right=newNode(4);root.right.right=newNode(9);consttarget=12;// Check if there are two elements in the BST// that added to "target"if(findTarget(root,target)){console.log("True");}else{console.log("False");}//Driver Code Ends
Output
True
[Expected Approach 2] Using Inorder Traversal and Two Pointers - 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 array. 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;classNode{public: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(){// Constructing the following BST:// 7// / \ // 3 8// / \ \ // 2 4 9Node*root=newNode(7);root->left=newNode(3);root->right=newNode(8);root->left->left=newNode(2);root->left->right=newNode(4);root->right->right=newNode(9);inttarget=12;// Check if there are two elements in the BST// that added to "target"if(findTarget(root,target))cout<<"True";elsecout<<"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){// Constructing the following BST:// 7// / \// 3 8// / \ \// 2 4 9Noderoot=newNode(7);root.left=newNode(3);root.right=newNode(8);root.left.left=newNode(2);root.left.right=newNode(4);root.right.right=newNode(9);inttarget=12;// Check if there are two elements in the BST// that added to "target"if(findTarget(root,target))System.out.println("True");elseSystem.out.println("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__":# Constructing the following BST:# 7# / \# 3 8# / \ \# 2 4 9root=Node(7)root.left=Node(3)root.right=Node(8)root.left.left=Node(2)root.left.right=Node(4)root.right.right=Node(9)target=12# Check if there are two elements in the BST# that added to "target"iffindTarget(root,target):print("True")else:print("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){// Constructing the following BST:// 7// / \// 3 8// / \ \// 2 4 9Noderoot=newNode(7);root.left=newNode(3);root.right=newNode(8);root.left.left=newNode(2);root.left.right=newNode(4);root.right.right=newNode(9);inttarget=12;// Check if there are two elements in the BST// that added to "target"if(findTarget(root,target))Console.WriteLine("True");elseConsole.WriteLine("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// Constructing the following BST:// 7// / \// 3 8// / \ \// 2 4 9constroot=newNode(7);root.left=newNode(3);root.right=newNode(8);root.left.left=newNode(2);root.left.right=newNode(4);root.right.right=newNode(9);consttarget=12;// Check if there are two elements in the BST// that added to "target"if(findTarget(root,target)){console.log("True");}else{console.log("False");}//Driver Code Ends