Find a pair with given sum in a Balanced BST
Last Updated : 20 Jan, 2025
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.
This problem is mainly an extension of the Find if there is a triplet in a Balanced BST that adds to zero. Here, we are not allowed to modify the BST.
[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> using namespace std; class Node { public: int data; Node* left; Node* right; Node(int d) { data = d; left = nullptr; right = nullptr; } }; //Driver Code Ends // Function to search for the Key in the BST bool search(Node* root, int key, Node* temp) { // If the root is NULL, return false if (root == nullptr) return false; // Start search from the root Node* current = root; // Traverse the BST to find the target value `k` while (current != nullptr) { // If Key is found if (current->data == key && current != temp) return true; // If key is smaller, move to the left else if (key < current->data) current = current->left; // If key is larger, move to the right else current = current->right; } // Return false if no match is found return false; } // Helper Function to find if there exists a pair // with a given sum in the BST bool findTargetRec(Node* root, Node* current, int target) { if (current == nullptr) return false; // Check if the complement of the current node value exists int complement = target - current->data; if (search(root, complement, current)) return true; // Check for the pair in left and right subtree return findTargetRec(root, current->left, target) || findTargetRec(root, current->right, target); } // Function to find if there exists a pair // with a given sum in the BST bool findTarget(Node* root, int target) { return findTargetRec(root, root, target); } //Driver Code Starts int main() { // BST structure // // 15 // / \ // 10 20 // / \ / \ // 8 12 16 25 Node* root = new Node(15); root->left = new Node(10); root->right = new Node(20); root->left->left = new Node(8); root->left->right = new Node(12); root->right->left = new Node(16); root->right->right = new Node(25); int target = 35; cout << (findTarget(root, target) ? "True" : "False"); return 0; } //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> typedef struct Node { int data; struct Node* left; struct Node* right; } Node; // Function to create a new node Node* newNode(int d) { Node* node = (Node*)malloc(sizeof(Node)); node->data = d; node->left = node->right = NULL; return node; } //Driver Code Ends // Function to search for the Key in the BST bool search(Node* root, int key, Node* temp) { // If the root is NULL, return false if (root == NULL) return false; // Start search from the root Node* current = root; // Traverse the BST to find the target value `key` while (current != NULL) { // If Key is found if (current->data == key && current != temp) return true; // If key is smaller, move to the left else if (key < current->data) current = current->left; // If key is larger, move to the right else current = current->right; } // Return false if no match is found return false; } // Helper Function to find if there exists a pair // with a given sum in the BST bool findTargetRec(Node* root, Node* current, int target) { if (current == NULL) return false; // Check if the complement of the current node value exists int complement = target - current->data; if (search(root, complement, current)) return true; // Check for the pair in left and right subtree return findTargetRec(root, current->left, target) || findTargetRec(root, current->right, target); } // Function to find if there exists a pair // with a given sum in the BST bool findTarget(Node* root, int target) { return findTargetRec(root, root, target); } //Driver Code Starts int main() { // BST structure // // 15 // / \ // 10 20 // / \ / \ // 8 12 16 25 Node* 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); int target = 35; // Print result printf("%s ", findTarget(root, target) ? "True" : "False"); return 0; } //Driver Code Ends
Java //Driver Code Starts // Java program to find a pair with given sum // in a Balanced BST class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; } } class GfG { //Driver Code Ends // Function to search for the Key in the BST static boolean search(Node root, int key, Node temp) { // If the root is NULL, return false if (root == null) return false; // Start search from the root Node current = root; // Traverse the BST to find the target value `key` while (current != null) { // If Key is found if (current.data == key && current != temp) return true; // If key is smaller, move to the left else if (key < current.data) current = current.left; // If key is larger, move to the right else current = current.right; } // Return false if no match is found return false; } // Helper Function to find if there exists a pair // with a given sum in the BST static boolean findTargetRec(Node root, Node current, int target) { if (current == null) return false; // Check if the complement of the current node value exists int complement = target - current.data; if (search(root, complement, current)) return true; // Check for the pair in left and right subtree return findTargetRec(root, current.left, target) || findTargetRec(root, current.right, target); } // Function to find if there exists a pair // with a given sum in the BST static boolean findTarget(Node root, int target) { return findTargetRec(root, root, target); } //Driver Code Starts public static void main(String[] args) { // BST structure // // 15 // / \ // 10 20 // / \ / \ // 8 12 16 25 Node root = new Node(15); root.left = new Node(10); root.right = new Node(20); root.left.left = new Node(8); root.left.right = new Node(12); root.right.left = new Node(16); root.right.right = new Node(25); int target = 35; // Print result 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 class Node: def __init__(self, data): self.data = data self.left = None self.right = None #Driver Code Ends # Function to search for the Key in the BST def search(root, key, temp): # If the root is NULL, return false if root is None: return False # Start search from the root current = root # Traverse the BST to find the target value `key` while current: # If Key is found if current.data == key and current != temp: return True # If key is smaller, move to the left elif key < current.data: current = current.left # If key is larger, move to the right else: current = current.right # Return false if no match is found return False # Helper Function to find if there exists a pair # with a given sum in the BST def findTargetRec(root, current, target): if current is None: return False # Check if the complement of the current node value exists complement = target - current.data if search(root, complement, current): return True # Check for the pair in left and right subtree return findTargetRec(root, current.left, target) or \ findTargetRec(root, current.right, target) # Function to find if there exists a pair # with a given sum in the BST def findTarget(root, target): return findTargetRec(root, root, target) #Driver Code Starts if __name__ == "__main__": # BST structure # # 15 # / \ # 10 20 # / \ / \ # 8 12 16 25 root = 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 = 35 print("True" if findTarget(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 System; class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; } } class GfG { //Driver Code Ends // Function to search for the Key in the BST static bool Search(Node root, int key, Node temp) { // If the root is NULL, return false if (root == null) return false; // Start search from the root Node current = root; // Traverse the BST to find the target value `key` while (current != null) { // If Key is found if (current.data == key && current != temp) return true; // If key is smaller, move to the left else if (key < current.data) current = current.left; // If key is larger, move to the right else current = current.right; } // Return false if no match is found return false; } // Helper Function to find if there exists a pair // with a given sum in the BST static bool FindTargetRec(Node root, Node current, int target) { if (current == null) return false; // Check if the complement of the current node value exists int complement = target - current.data; if (Search(root, complement, current)) return true; // Check for the pair in left and right subtree return FindTargetRec(root, current.left, target) || FindTargetRec(root, current.right, target); } // Function to find if there exists a pair // with a given sum in the BST static bool FindTarget(Node root, int target) { return FindTargetRec(root, root, target); } //Driver Code Starts static void Main(string[] args) { // BST structure // // 15 // / \ // 10 20 // / \ / \ // 8 12 16 25 Node root = new Node(15); root.left = new Node(10); root.right = new Node(20); root.left.left = new Node(8); root.left.right = new Node(12); root.right.left = new Node(16); root.right.right = new Node(25); int target = 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 class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } } //Driver Code Ends // Function to search for the Key in the BST function search(root, key, temp) { // If the root is NULL, return false if (root === null) return false; // Start search from the root let current = root; // Traverse the BST to find the target value `key` while (current !== null) { // If Key is found if (current.data === key && current !== temp) return true; // If key is smaller, move to the left else if (key < current.data) current = current.left; // If key is larger, move to the right else current = current.right; } // Return false if no match is found return false; } // Helper Function to find if there exists a pair // with a given sum in the BST function findTargetRec(root, current, target) { if (current === null) return false; // Check if the complement of the current node value exists const complement = target - current.data; if (search(root, complement, current)) return true; // Check for the pair in left and right subtree return findTargetRec(root, current.left, target) || findTargetRec(root, current.right, target); } // Function to find if there exists a pair // with a given sum in the BST function findTarget(root, target) { return findTargetRec(root, root, target); } //Driver Code Starts // Driver Code // BST structure // // 15 // / \ // 10 20 // / \ / \ // 8 12 16 25 const root = new Node(15); root.left = new Node(10); root.right = new Node(20); root.left.left = new Node(8); root.left.right = new Node(12); root.right.left = new Node(16); root.right.right = new Node(25); const target = 35; console.log(findTarget(root, target) ? "True" : "False"); //Driver Code Ends
[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> using namespace std; struct Node { int data; Node* left; Node* right; Node(int d) { data = d; left = nullptr; right = nullptr; } }; //Driver Code Ends // Function to perform Inorder traversal and store the // elements in a vector void inorderTraversal(Node* root, vector<int>& inorder) { if (root == nullptr) return; inorderTraversal(root->left, inorder); // Store the current node's value inorder.push_back(root->data); inorderTraversal(root->right, inorder); } // Function to find if there exists a pair with a // given sum in the BST bool findTarget(Node* root, int target) { // Create an auxiliary array and store Inorder traversal vector<int> inorder; inorderTraversal(root, inorder); // Use two-pointer technique to find the pair with given sum int left = 0, right = inorder.size() - 1; while (left < right) { int currentSum = inorder[left] + inorder[right]; // If the pair is found, return true if (currentSum == target) return true; // If the current sum is less than the target, // move the left pointer if (currentSum < target) left++; // If the current sum is greater than // the target, move the right pointer else right--; } return false; } //Driver Code Starts int main() { // BST structure // // 15 // / \ // 10 20 // / \ / \ // 8 12 16 25 Node* root = new Node(15); root->left = new Node(10); root->right = new Node(20); root->left->left = new Node(8); root->left->right = new Node(12); root->right->left = new Node(16); root->right->right = new Node(25); int target = 35; cout << (findTarget(root, target) ? "True" : "False"); return 0; } //Driver Code Ends
Java //Driver Code Starts // Java program to find a pair with given sum in a Balanced BST // Using Inorder Traversal import java.util.ArrayList; class Node { int data; Node left, right; Node(int data) { this.data = data; left = null; right = null; } } class GfG { //Driver Code Ends // Function to perform Inorder traversal and store the // elements in an array static void inorderTraversal(Node root, ArrayList<Integer> inorder) { if (root == null) return; inorderTraversal(root.left, inorder); // Store the current node's value inorder.add(root.data); inorderTraversal(root.right, inorder); } // Function to find if there exists a pair with a // given sum in the BST static boolean findTarget(Node root, int target) { // Create an auxiliary array and store Inorder traversal ArrayList<Integer> inorder = new ArrayList<>(); inorderTraversal(root, inorder); // Use two-pointer technique to find the pair with given sum int left = 0, right = inorder.size() - 1; while (left < right) { int currentSum = inorder.get(left) + inorder.get(right); // If the pair is found, return true if (currentSum == target) return true; // If the current sum is less than the target, // move the left pointer if (currentSum < target) left++; // If the current sum is greater than // the target, move the right pointer else right--; } return false; } //Driver Code Starts public static void main(String[] args) { // BST structure // // 15 // / \ // 10 20 // / \ / \ // 8 12 16 25 Node root = new Node(15); root.left = new Node(10); root.right = new Node(20); root.left.left = new Node(8); root.left.right = new Node(12); root.right.left = new Node(16); root.right.right = new Node(25); int target = 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 Traversal class Node: def __init__(self, data): self.data = data self.left = None self.right = None #Driver Code Ends # Function to perform Inorder traversal and store the # elements in an array def inorderTraversal(root, inorder): if root is None: return inorderTraversal(root.left, inorder) # Store the current node's value inorder.append(root.data) inorderTraversal(root.right, inorder) # Function to find if there exists a pair with a # given sum in the BST def findTarget(root, target): # Create an auxiliary array and store Inorder traversal inorder = [] inorderTraversal(root, inorder) # Use two-pointer technique to find the pair with given sum left, right = 0, len(inorder) - 1 while left < right: currentSum = inorder[left] + inorder[right] # If the pair is found, return true if currentSum == target: return True # If the current sum is less than the target, # move the left pointer if currentSum < target: left += 1 # If the current sum is greater than # the target, move the right pointer else: right -= 1 return False #Driver Code Starts if __name__ == "__main__": # BST structure # # 15 # / \ # 10 20 # / \ / \ # 8 12 16 25 root = 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 = 35 print("True" if findTarget(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 Traversal using System; using System.Collections.Generic; class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; } } class GfG { //Driver Code Ends // Function to perform Inorder traversal and store the // elements in a list static void InorderTraversal(Node root, List<int> inorder) { if (root == null) return; InorderTraversal(root.left, inorder); // Store the current node's value inorder.Add(root.data); InorderTraversal(root.right, inorder); } // Function to find if there exists a pair with a // given sum in the BST static bool FindTarget(Node root, int target) { // Create an auxiliary list and store Inorder traversal List<int> inorder = new List<int>(); InorderTraversal(root, inorder); // Use two-pointer technique to find the pair with given sum int left = 0, right = inorder.Count - 1; while (left < right) { int currentSum = inorder[left] + inorder[right]; // If the pair is found, return true if (currentSum == target) return true; // If the current sum is less than the target, // move the left pointer if (currentSum < target) left++; // If the current sum is greater than // the target, move the right pointer else right--; } return false; } //Driver Code Starts static void Main(string[] args) { // BST structure // // 15 // / \ // 10 20 // / \ / \ // 8 12 16 25 Node root = new Node(15); root.left = new Node(10); root.right = new Node(20); root.left.left = new Node(8); root.left.right = new Node(12); root.right.left = new Node(16); root.right.right = new Node(25); int target = 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 Traversal class Node { 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 array function inorderTraversal(root, inorder) { if (root === null) return; inorderTraversal(root.left, inorder); // Store the current node's value inorder.push(root.data); inorderTraversal(root.right, inorder); } // Function to find if there exists a pair with a // given sum in the BST function findTarget(root, target) { // Create an auxiliary array and store Inorder traversal let inorder = []; inorderTraversal(root, inorder); // Use two-pointer technique to find the pair with given sum let left = 0, right = inorder.length - 1; while (left < right) { let currentSum = inorder[left] + inorder[right]; // If the pair is found, return true if (currentSum === target) return true; // If the current sum is less than the target, // move the left pointer if (currentSum < target) left++; // If the current sum is greater than // the target, move the right pointer else right--; } return false; } //Driver Code Starts // Driver Code // BST structure // // 15 // / \ // 10 20 // / \ / \ // 8 12 16 25 const root = new Node(15); root.left = new Node(10); root.right = new Node(20); root.left.left = new Node(8); root.left.right = new Node(12); root.right.left = new Node(16); root.right.right = new Node(25); const target = 35; console.log(findTarget(root, target) ? "True" : "False"); //Driver Code Ends
Similar Reads
Binary Search Tree A Binary Search Tree (BST) is a type of binary tree data structure in which each node contains a unique key and satisfies a specific ordering property:All nodes in the left subtree of a node contain values strictly less than the nodeâs value. All nodes in the right subtree of a node contain values s
4 min read
Introduction to Binary Search Tree Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
3 min read
Applications of BST Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward.The left subtree of a node contains only node
3 min read
Applications, Advantages and Disadvantages of Binary Search Tree A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
2 min read
Insertion in Binary Search Tree (BST) Given a BST, the task is to insert a new node in this BST.Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is fo
15 min read
Searching in Binary Search Tree (BST) Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
7 min read
Deletion in Binary Search Tree (BST) Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios:Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BSTDeleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node w
10 min read
Binary Search Tree (BST) Traversals â Inorder, Preorder, Post Order Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: A Binary Search TreeOutput: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 1
10 min read
Balance a Binary Search Tree Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height.Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.Input: Output: Explanation: The above u
10 min read
Self-Balancing Binary Search Trees Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
4 min read