The Wayback Machine - https://web.archive.org/web/20250109005145/https://www.geeksforgeeks.org/find-a-pair-with-given-sum-in-bst/
Open In App

Find a pair with given sum in a Balanced BST

Last Updated : 12 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a Balanced Binary Search Tree and a target sum, the task is to check if there is a pair with a 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^2 * h) Time and O(h) Space

The idea is to consider each node in the BST and search for its 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++
// C++ code to find a pair with given sum
// in a Balanced BST

#include <bits/stdc++.h>
using namespace std;


class Node {
      
  public:
    int data;
    Node* left;
    Node* right;
    Node(int d) {
        data = d;
        left = nullptr;
        right = nullptr;
    }
};

// Function to search for the target value in the BST
bool search(Node* root, Node* temp, int k) {
    
    // If the root is NULL, return false
    if (root == nullptr)
        return false;

    // Start searching from the root
    Node* current = root;
    bool flag = false;

    // Traverse the BST to find the target value `k`
    while (current != nullptr && !flag) {
        
        // If a pair is found
        if (current->data == k && temp != current) { 
            flag = true;
            return true;
        }
        // If target is smaller, move to the left
        else if (k < current->data) 
            current = current->left;
        else 
            // If target is larger, move to the right
            current = current->right;
    }
    // Return false if no match is found
    return false; 
}

// Function to find if there exists a pair 
// with a given sum in the BST
bool isPairPresent(Node* root, Node* temp, int target) {
    if (temp == nullptr)
        return false;

    // Check if the complement of the current node value exists
    return search(root, temp, target - temp->data)
        || isPairPresent(root, temp->left, target)
        || isPairPresent(root, temp->right, target);
}


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;

    bool test = isPairPresent(root, root, target);

    if (!test) {
        cout << "false" << endl;
    }
    else {
        cout << "true" << endl;
    }
    return 0;
}
Java
// Java code to find a pair with given 
// sum in a Balanced BST

class Node {
    int data;
    Node left, right;

    Node(int d) {
        data = d;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to search for the target value in the BST
    static boolean search(Node root, Node temp, int k) {

        // If the root is NULL, return false
        if (root == null)
            return false;

        // Start searching from the root
        Node current = root;
        boolean flag = false;

        // Traverse the BST to find the target value `k`
        while (current != null && !flag) {

            // If a pair is found
            if (current.data == k && temp != current) {
                flag = true;
                return true;
            }
          
            // If target is smaller, move to the left
            else if (k < current.data)
                current = current.left;
            else
                // If target is larger, move to the right
                current = current.right;
        }
      
        // Return false if no match is found
        return false; 
    }

    // Function to find if there exists a pair with a given sum in the BST
    static boolean isPairPresent(Node root, Node temp, int target) {
        if (temp == null)
            return false;

        // Check if the complement of the current node value exists
        return search(root, temp, target - temp.data)
                || isPairPresent(root, temp.left, target)
                || isPairPresent(root, temp.right, target);
    }

    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;
        boolean test = isPairPresent(root, root, target);

        if (!test) {
            System.out.println("false");
        } else {
            System.out.println("true");
        }
    }
}
Python
# Python code 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

# Function to search for the target 
# value in the BST
def search(root, temp, k):
    
    # If the root is NULL, return false
    if root is None:
        return False

    # Start searching from the root
    current = root
    flag = False

    # Traverse the BST to find the target value `k`
    while current is not None and not flag:
        
        # If a pair is found
        if current.data == k and temp != current:
            flag = True
            return True
          
        # If target is smaller, move to the left
        elif k < current.data:
            current = current.left
        else:
          
            # If target is larger, move to the right
            current = current.right
     # Return false if no match is found
    return False 

# Function to find if there exists a pair with a
# given sum in the BST
def isPairPresent(root, temp, target):
    if temp is None:
        return False

    # Check if the complement of the current
    # node value exists
    return search(root, temp, target - temp.data) or \
           isPairPresent(root, temp.left, target) or \
           isPairPresent(root, temp.right, target)


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
    test = isPairPresent(root, root, target)

    if not test:
        print("false")
    else:
        print("true")
C#
// C# code 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 = null;
        right = null;
    }
}

class GfG {

    // Function to search for the target value in the BST
    static bool Search(Node root, Node temp, int k) {

        // If the root is NULL, return false
        if (root == null)
            return false;

        // Start searching from the root
        Node current = root;
        bool flag = false;

        // Traverse the BST to find the target value `k`
        while (current != null && !flag) {

            // If a pair is found
            if (current.data == k && temp != current) {
                flag = true;
                return true;
            }
          
            // If target is smaller, move to the left
            else if (k < current.data)
                current = current.left;
            else
              
                // If target is larger, move to the right
                current = current.right;
        }
      
        // Return false if no match is found
        return false; 
    }

    // Function to find if there exists a pair with a given
      // sum in the BST
    static bool IsPairPresent(Node root, Node temp, int target) {
        if (temp == null)
            return false;

        // Check if the complement of the current node
          // value exists
        return Search(root, temp, target - temp.data)
                || IsPairPresent(root, temp.left, target)
                || IsPairPresent(root, temp.right, target);
    }

    static void 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;
        bool test = IsPairPresent(root, root, target);

        if (!test) {
            Console.WriteLine("false");
        } else {
            Console.WriteLine("true");
        }
    }
}
JavaScript
// JavaScript code to find a pair with given 
// sum in a Balanced BST

class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Function to search for the target 
// value in the BST
function search(root, temp, k) {

    // If the root is NULL, return false
    if (root === null) {
        return false;
    }

    // Start searching from the root
    let current = root;
    let flag = false;

    // Traverse the BST to find the target value `k`
    while (current !== null && !flag) {

        // If a pair is found
        if (current.data === k && temp !== current) {
            flag = true;
            return true;
        }
        
        // If target is smaller, move to the left
        else if (k < current.data) {
            current = current.left;
        } else {
        
            // If target is larger, move to the right
            current = current.right;
        }
    }
    // Return false if no match is found
    return false; 
}

// Function to find if there exists a pair with
// a given sum in the BST
function isPairPresent(root, temp, target) {
    if (temp === null) {
        return false;
    }

    // Check if the complement of the current 
    // node value exists
    return search(root, temp, target - temp.data)
        || isPairPresent(root, temp.left, target)
        || isPairPresent(root, temp.right, target);
}

// BST structure
//
//        15
//       /  \
//     10   20
//    / \   / \
//   8  12 16 25

let 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);

let target = 35;
let test = isPairPresent(root, root, target);

if (!test) {
    console.log("false");
} else {
    console.log("true");
}

Output
true

[Optimal 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. Once we have the Inorder traversal, we can pair in O(n) time (See Two sum for details).

Follow the steps below to solve the problem:

  • Perform an inorder traversal of the BST to store elements in a sorted list.
  • Use two pointers, one at the beginning (left) and one at the end (right) of the list.
  • Calculate the sum of the elements at the two pointers.
  • If the sum equals the target, return true. If the sum is less, move the left pointer forward. If the sum is more, move the right pointer backward.
  • Repeat until the pointers meet or the pair is found. return false if no pair is found.

Below is the implementation of the above approach:

C++
// C++ code to find a pair with given sum
// in a Balanced BST

#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;

    Node(int d) {
        data = d;
        left = nullptr;
        right = nullptr;
    }
};


// Function to perform Inorder traversal and store the \
// elements in a vector
void inorderTraversal(Node* root, vector<int>& inorder) {
    if (root == nullptr)
        return;

    // Traverse the left subtree
    inorderTraversal(root->left, inorder);

    // Store the current node's value
    inorder.push_back(root->data);

    // Traverse the right subtree
    inorderTraversal(root->right, inorder);
}

// Function to find if there exists a pair with a 
// given sum in the BST
bool isPairPresent(Node* root, Node* temp, 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;
    int right = inorder.size() - 1;

    while (left < right) {
        int currentSum = inorder[left] + inorder[right];

        // If the pair is found
        if (currentSum == target) {
            return true;
        }

        // If the current sum is less than the target, 
        // move the left pointer
        if (currentSum < target)
            left++;
        else
          
            // If the current sum is greater than 
            // the target, move the right pointer
            right--;
    }

    return false;
}


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;

    bool test = isPairPresent(root, root, target);

    if (!test) {
        cout << "false" << endl;
    }
    else {
        cout << "true" << endl;
    }
    return 0;
}
Java
// Java code to find a pair with given sum in a
// Balanced BST
import java.util.ArrayList;

class Node {
    int data;
    Node left, right;
    Node(int d) {
        data = d;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to perform Inorder traversal and 
    // store the elements in an ArrayList
    static void inorderTraversal(Node root, 
                                 ArrayList<Integer> inorder) {
        if (root == null)
            return;

        // Traverse the left subtree
        inorderTraversal(root.left, inorder);

        // Store the current node's value
        inorder.add(root.data);

        // Traverse the right subtree
        inorderTraversal(root.right, inorder);
    }

    // Function to find if there exists a pair 
    // with a given sum in the BST
    static boolean isPairPresent(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;
        int right = inorder.size() - 1;

        while (left < right) {
            int currentSum = inorder.get(left) + inorder.get(right);

            // If the pair is found
            if (currentSum == target) {
                return true;
            }

            // If the current sum is less than the target,
            // move the left pointer
            if (currentSum < target)
                left++;
            else
              
                // If the current sum is greater than the target, 
                  // move the right pointer
                right--;
        }
      
        return false;
    }

    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;
        boolean test = isPairPresent(root, target);

        if (!test) {
            System.out.println("false");
        } else {
            System.out.println("true");
        }
    }
}
Python
# Python code 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


# Function to perform Inorder traversal and 
# store the elements in a list
def inorderTraversal(root, inorder):
    if root is None:
        return

    # Traverse the left subtree
    inorderTraversal(root.left, inorder)

    # Store the current node's value
    inorder.append(root.data)

    # Traverse the right subtree
    inorderTraversal(root.right, inorder)


# Function to find if there exists a pair with a
# given sum in the BST
def isPairPresent(root, target):
  
    # Create an auxiliary list and store Inorder
    # traversal
    inorder = []
    inorderTraversal(root, inorder)

    # Use two-pointer technique to find the pair
    # with given sum
    left = 0
    right = len(inorder) - 1

    while left < right:
        currentSum = inorder[left] + inorder[right]

        # If the pair is found
        if currentSum == target:
            return True

        # If the current sum is less than the target,
        # move the left pointer
        if currentSum < target:
            left += 1
        else:
            # If the current sum is greater than the target,
            # move the right pointer
            right -= 1

    return False


# 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
test = isPairPresent(root, target)

if not test:
    print("false")
else:
    print("true")
C#
// C# code to find a pair with given sum 
// in a Balanced BST
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;
    public Node(int d) {
        data = d;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to perform Inorder traversal and store 
      // the elements in a List
    static void inorderTraversal(Node root,
                                 List<int> inorder) {
        if (root == null)
            return;

        // Traverse the left subtree
        inorderTraversal(root.left, inorder);

        // Store the current node's value
        inorder.Add(root.data);

        // Traverse the right subtree
        inorderTraversal(root.right, inorder);
    }

    // Function to find if there exists a pair with a
      // given sum in the BST
    static bool isPairPresent(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;
        int right = inorder.Count - 1;

        while (left < right) {
            int currentSum = inorder[left] + inorder[right];

            // If the pair is found
            if (currentSum == target) {
                return true;
            }

            // If the current sum is less than the target,
            // move the left pointer
            if (currentSum < target)
                left++;
            else
              
                // If the current sum is greater than the target,
                  // move the right pointer
                right--;
        }
      
        return false;
    }

    static void 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;
        bool test = isPairPresent(root, target);

        if (!test) {
            Console.WriteLine("false");
        } else {
            Console.WriteLine("true");
        }
    }
}
JavaScript
// JavaScript code to find a pair with given 
// sum in a Balanced BST

function Node(data) {
    this.data = data;
    this.left = null;
    this.right = null;
}

// Function to perform Inorder traversal and store the
// elements in an array
function inorderTraversal(root, inorder) {
    if (root === null) return;

    // Traverse the left subtree
    inorderTraversal(root.left, inorder);

    // Store the current node's value
    inorder.push(root.data);

    // Traverse the right subtree
    inorderTraversal(root.right, inorder);
}

// Function to find if there exists a pair with a 
// given sum in the BST
function isPairPresent(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;
    let right = inorder.length - 1;

    while (left < right) {
        let currentSum = inorder[left] + inorder[right];

        // If the pair is found
        if (currentSum === target) {
            return true;
        }

        // If the current sum is less than the target,
        // move the left pointer
        if (currentSum < target)
            left++;
        else
            // If the current sum is greater than the target,
            // move the right pointer
            right--;
    }

    return false;
}

// BST structure
//
//        15
//       /  \
//     10   20
//    / \   / \
//   8  12 16 25

let 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);

let target = 35;

let test = isPairPresent(root, target);

if (!test) {
    console.log("false");
} else {
    console.log("true");
}

Output
true

[Expected approach] Using Stack – O(n) Time and O(h) Space

A space optimized solution is discussed in Find if there is a triplet in a Balanced BST that adds to zero post. The idea was to first in-place convert BST to Doubly Linked List (DLL), then find pair in sorted DLL in O(n) time. This solution takes O(n) time and O(Logn) extra space, but it modifies the given BST.

The solution discussed below takes O(n) time, O(Logn) space and doesn’t modify BST. The idea is same as finding the pair in sorted array Refer to Pair with given Sum (Two Sum).

The idea is to use two stacks to perform in-order traversals in both normal and reverse directions of the BST. Compare the sum of the top elements from each stack to find a pair that matches the target. We traverse BST in Normal Inorder and Reverse Inorder simultaneously. In reverse inorder, we start from the rightmost node which is the maximum value node. In normal inorder, we start from the left most node which is minimum value node. We add sum of current nodes in both traversals and compare this sum with given target sum. If the sum is same as target sum, we return true. If the sum is more than target sum, we move to next node in reverse inorder traversal, otherwise we move to next node in normal inorder traversal. If any of the traversals is finished without finding a pair, we return false.

Below is the implementation of the above approach:

C++
// C++ code of check is target is present 
// or not in BST

#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;

    Node(int d) {
        data = d;
        left = nullptr;
        right = nullptr;
    }
};

// Function to perform inorder traversal
void inorderPush(Node* node, stack<Node*>& s, bool reverse) {
    while (node) {
        s.push(node);
        
        // Reverse inorder if reverse is true
        node = reverse ? node->right : node->left; 
    }
}

// Function to find if there exists a pair 
// with a given sum in the BST
bool isPairPresent(Node* root, int target) {
    if (!root) return false;

    stack<Node*> normalStack;  
    stack<Node*> reverseStack;  

    // Initialize both stacks
    inorderPush(root, normalStack, false);  
    inorderPush(root, reverseStack, true); 

    while (!normalStack.empty() && !reverseStack.empty()) {
        Node* left = normalStack.top();
        Node* right = reverseStack.top();

        int currentSum = left->data + right->data;

        // If the pair is found
        if (currentSum == target) {
            return true;
        }

        // If the current sum is less than the target, 
        // move the normal inorder pointer
        if (currentSum < target) {
            
            // Move to the next node in normal inorder
            normalStack.pop();    
            
             // Push the right child (next node in normal order)
            inorderPush(left->right, normalStack, false); 
        } 
      
        // If the current sum is more than the target, 
        // move the reverse inorder pointer
        else {
            
            // Move to the next node in reverse inorder
            reverseStack.pop();   
            
            // Push the left child (next node in reverse order)
            inorderPush(right->left, reverseStack, true);  
        }
    }

    // If no pair is found
    return false;
}

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;
    bool test = isPairPresent(root, target);

    if (!test) {
        cout << "false" << endl;
    }
    else {
        cout << "true" << endl;
    }
    return 0;
}
Java
// Java code of check is target is present 
// or not in BST

import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int d) {
        data = d;
        left = right = null;
    }
}

class GfG {

    // Function to perform inorder traversal
    static void inorderPush(Node node, Stack<Node> s,
                            boolean reverse) {
        while (node != null) {
            s.push(node);

            // Reverse inorder if reverse is true
            node = reverse ? node.right : node.left;
        }
    }

    // Function to find if there exists a pair 
    // with a given sum in the BST
    static boolean isPairPresent(Node root, int target) {
        if (root == null) return false;

        Stack<Node> normalStack = new Stack<>();
        Stack<Node> reverseStack = new Stack<>();

        // Initialize both stacks
        inorderPush(root, normalStack, false);
        inorderPush(root, reverseStack, true);

        while (!normalStack.isEmpty() && !reverseStack.isEmpty()) {
            Node left = normalStack.peek();
            Node right = reverseStack.peek();

            int currentSum = left.data + right.data;

            // If the pair is found
            if (currentSum == target) {
                return true;
            }

            // If the current sum is less than the target, 
            // move the normal inorder pointer
            if (currentSum < target) {
              
                // Move to the next node in normal inorder
                normalStack.pop();

                // Push the right child (next node in normal order)
                inorderPush(left.right, normalStack, false);
            }
          
            // If the current sum is more than the target, 
            // move the reverse inorder pointer
            else {
              
                // Move to the next node in reverse inorder
                reverseStack.pop();

                // Push the left child (next node in reverse order)
                inorderPush(right.left, reverseStack, true);
            }
        }

        // If no pair is found
        return false;
    }

    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;
        boolean test = isPairPresent(root, target);

        if (!test) {
            System.out.println("false");
        } else {
            System.out.println("true");
        }
    }
}
Python
# Python code of check is target is present 
# or not in BST
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Function to perform inorder traversal
def inorder_push(node, stack, reverse):
    while node:
        stack.append(node)

        # Reverse inorder if reverse is true
        node = node.right if reverse else node.left

# Function to find if there exists a pair 
# with a given sum in the BST
def is_pair_present(root, target):
    if not root:
        return False

    normal_stack = []
    reverse_stack = []

    # Initialize both stacks
    inorder_push(root, normal_stack, False)
    inorder_push(root, reverse_stack, True)

    while normal_stack and reverse_stack:
        left = normal_stack[-1]
        right = reverse_stack[-1]

        current_sum = left.data + right.data

        # If the pair is found
        if current_sum == target:
            return True

        # If the current sum is less than the target, 
        # move the normal inorder pointer
        if current_sum < target:
          
            # Move to the next node in normal inorder
            normal_stack.pop()
            
            # Push the right child (next node in normal order)
            inorder_push(left.right, normal_stack, False)
            
        # If the current sum is more than the target, 
        # move the reverse inorder pointer
        else:
          
            # Move to the next node in reverse inorder
            reverse_stack.pop()

            # Push the left child (next node in reverse order)
            inorder_push(right.left, reverse_stack, True)

    # If no pair is found
    return False


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
    if is_pair_present(root, target):
        print("true")
    else:
        print("false")
C#
// C# code of check is target is present 
// or not in BST

using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int d) {
        data = d;
        left = right = null;
    }
}

class GfG {

    // Function to perform inorder traversal
    static void InorderPush(Node node, Stack<Node> s, bool reverse) {
        while (node != null) {
            s.Push(node);

            // Reverse inorder if reverse is true
            node = reverse ? node.right : node.left;
        }
    }

    // Function to find if there exists a pair 
    // with a given sum in the BST
    static bool IsPairPresent(Node root, int target) {
        if (root == null) return false;

        Stack<Node> normalStack = new Stack<Node>();
        Stack<Node> reverseStack = new Stack<Node>();

        // Initialize both stacks
        InorderPush(root, normalStack, false);
        InorderPush(root, reverseStack, true);

        while (normalStack.Count > 0 && reverseStack.Count > 0) {
            Node left = normalStack.Peek();
            Node right = reverseStack.Peek();

            int currentSum = left.data + right.data;

            // If the pair is found
            if (currentSum == target) {
                return true;
            }

            // If the current sum is less than the target, 
            // move the normal inorder pointer
            if (currentSum < target) {
                normalStack.Pop();

                // Push the right child (next node in normal order)
                InorderPush(left.right, normalStack, false);
            }
          
            // If the current sum is more than the target, 
            // move the reverse inorder pointer
            else {
                reverseStack.Pop();

                // Push the left child 
                  // (next node in reverse order)
                InorderPush(right.left, reverseStack, true);
            }
        }

        // If no pair is found
        return false;
    }

    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;
        if (IsPairPresent(root, target)) {
            Console.WriteLine("true");
        } else {
            Console.WriteLine("false");
        }
    }
}
JavaScript
// Javascript code of check is target is present 
// or not in BST

class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Function to perform inorder traversal
function inorderPush(node, stack, reverse) {
    while (node) {
        stack.push(node);

        // Reverse inorder if reverse is true
        node = reverse ? node.right : node.left;
    }
}

// Function to find if there exists a pair 
// with a given sum in the BST
function isPairPresent(root, target) {
    if (!root) return false;

    let normalStack = [];
    let reverseStack = [];

    // Initialize both stacks
    inorderPush(root, normalStack, false);
    inorderPush(root, reverseStack, true);

    while (normalStack.length > 0 && reverseStack.length > 0) {
        let left = normalStack[normalStack.length - 1];
        let right = reverseStack[reverseStack.length - 1];

        let currentSum = left.data + right.data;

        // If the pair is found
        if (currentSum === target) {
            return true;
        }

        // If the current sum is less than the target, 
        // move the normal inorder pointer
        if (currentSum < target) {
            normalStack.pop();

            // Push the right child (next node in normal order)
            inorderPush(left.right, normalStack, false);
        }
        
        // If the current sum is more than the target, 
        // move the reverse inorder pointer
        else {
            reverseStack.pop();

            // Push the left child (next node in reverse order)
            inorderPush(right.left, reverseStack, true);
        }
    }

    // If no pair is found
    return false;
}

// 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);

let target = 35;
if (isPairPresent(root, target)) {
    console.log("true");
} else {
    console.log("false");
}

Output
true


Next Article

Similar Reads

three90RightbarBannerImg