Open In App

Find a pair with given sum in a Balanced BST

Last Updated : 20 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:  

Find-a-pair-with-given-sum-in-a-Balanced-BST

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

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>
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

Output
True


Next Article

Similar Reads