Check if a triplet with given sum exists in BST

Last Updated : 11 Jul, 2025

Given a Binary Search Tree and a sum. The task is to check if any triplet (group of 3 elements) exists in the BST with the given sum.

Examples: 

Input : sum= 21

Check-if-a-triplet-with-given-sum-exists-in-BST


Output : true
Explanation: There exists a triplet (7, 3, 11) in the above given BST with sum 21.

Input : sum= 101

Remove-all-leaf-nodes-from-the-binary-search-tree-1

Output : false

Approach:

It is known that elements in the inorder traversal of BST are sorted in increasing order. So, the idea is to do inorder traversal on the given BST and store the elements in a array. Now the task reduces to check for a triplet with given sum in a sorted array.

Below is the implementation of the above approach: 

C++
// C++ program to check if a triplet with
// given target exists in the BST or not

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

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

// A utility function to do inorder traversal
// of the BST and store values in a vector
void inorder(Node* curr, vector<int>& vec) {
    if (curr != nullptr) {
        inorder(curr->left, vec);
        vec.push_back(curr->data);
        inorder(curr->right, vec);
    }
}

// Function to check if a triplet with given sum
// exists in the BST or not
bool checkForTriplet(Node* root, int sum) {

    // Vector to store the inorder traversal
    // of the BST
    vector<int> arr;

    // Call inorder() to do the inorder
    // on the BST and store it in vec
    inorder(root, arr);

    // Now, check if any triplet with given sum
    // exists in the BST or not
    int l, r;

    // Now fix the first element one by one and find the
    // other two elements
    for (int i = 0; i < arr.size() - 2; i++) {

        // To find the other two elements, start two index
        // variables from two corners of the array and move
        // them toward each other
        l = i + 1; 
      
        // index of the last element
        r = arr.size() - 1;
        while (l < r) {
          	
          	// If we find pair with target - arr[i]
          	// then return true
            if (arr[l] + arr[r] == sum - arr[i]) {
                return true;
            }
            else if (arr[l] + arr[r] < sum - arr[i])
                l++;
            else
                r--;
        }
    }
    return false;
}

int main() {
  
    // creating the following BST 
    //      50 
    //    /     \ 
    //   30     70 
    //   / \   / \ 
    //  20 40 60 80 
    Node* root = new Node(50);
    root->left = new Node(30);
    root->right = new Node(70);
    root->left->left = new Node(20);
    root->left->right = new Node(40);
    root->right->left = new Node(60);
    root->right->right = new Node(80);

    int sum = 120;

    if (checkForTriplet(root, sum))
        cout << "true";
    else
        cout << "false";

    return 0;
}
Java
// Java program to check if a triplet with
// given target exists in the BST or not

import java.util.*;

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

class GfG {
    
    // A utility function to do inorder traversal
    // of the BST and store values in a vector
    static void inorder(Node curr, ArrayList<Integer> arr) {
        if (curr != null) {
            inorder(curr.left, arr);
            arr.add(curr.data);
            inorder(curr.right, arr);
        }
    }

    // Function to check if a triplet with given SUM
    // exists in the BST or not
    static boolean checkForTriplet(Node root, int sum) {

        // Vector to store the inorder traversal
        // of the BST
        ArrayList<Integer> arr = new ArrayList<>();

        // Call inorder() to do the inorder
        // on the BST and store it in arr
        inorder(root, arr);

        // Now, check if any triplet with given sum
        // exists in the BST or not
        int l, r;

        // Now fix the first element one by one and find the
        // other two elements
        for (int i = 0; i < arr.size() - 2; i++) {

            // To find the other two elements, start two index
            // variables from two corners of the array and move
            // them toward each other
            l = i + 1;

            // index of the last element
            r = arr.size() - 1;
            while (l < r) {

                // If we find pair with target - arr[i] 
              	// then return true
                if (arr.get(l) + arr.get(r) == sum - arr.get(i)) {
                    return true;
                }
                else if (arr.get(l) + arr.get(r) < sum - arr.get(i))
                    l++;
                else
                    r--;
            }
        }

        return false;
    }

    public static void main(String[] args) {
      
        // creating the following BST 
        //      50 
        //    /     \ 
        //   30     70 
        //   / \   / \ 
        //  20 40 60 80 
        Node root = new Node(50);
        root.left = new Node(30);
        root.right = new Node(70);
        root.left.left = new Node(20);
        root.left.right = new Node(40);
        root.right.left = new Node(60);
        root.right.right = new Node(80);

        int sum = 120;

        if (checkForTriplet(root, sum))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
# Python program to check if a triplet with
# given target exists in the BST or not

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# A utility function to do inorder traversal
# of the BST and store values in a list
def inorder(curr, arr):
    if curr is not None:
        inorder(curr.left, arr)
        arr.append(curr.data)
        inorder(curr.right, arr)

# Function to check if a triplet with given SUM
# exists in the BST or not
def checkForTriplet(root, sum):

    # List to store the inorder traversal
    # of the BST
    arr = []

    # Call inorder() to do the inorder
    # on the BST and store it in arr
    inorder(root, arr)

    # Now, check if any triplet with given sum
    # exists in the BST or not
    for i in range(len(arr) - 2):

        l = i + 1
        r = len(arr) - 1

        while l < r:
            if arr[l] + arr[r] == sum - arr[i]:
                return True
            elif arr[l] + arr[r] < sum - arr[i]:
                l += 1
            else:
                r -= 1

    return False

if __name__ == "__main__":
  
    # creating the following BST 
    #      50 
    #    /     \ 
    #   30     70 
    #   / \   / \ 
    #  20 40 60 80 
    root = Node(50)
    root.left = Node(30)
    root.right = Node(70)
    root.left.left = Node(20)
    root.left.right = Node(40)
    root.right.left = Node(60)
    root.right.right = Node(80)

    sum = 120

    if checkForTriplet(root, sum):
        print("true")
    else:
        print("false")
C#
// C# program to check if a triplet with
// given target exists in the BST or not

using System;
using System.Collections.Generic;

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

class GfG {

    // A utility function to do inorder traversal
    // of the BST and store values in a list
    static void Inorder(Node curr, List<int> arr) {
        if (curr != null) {
            Inorder(curr.left, arr);
            arr.Add(curr.data);
            Inorder(curr.right, arr);
        }
    }

    // Function to check if a triplet with given sum
    // exists in the BST or not
    static bool CheckForTriplet(Node root, int sum) {

        // List to store the inorder traversal
        // of the BST
        List<int> arr = new List<int>();

        // Call Inorder() to do the inorder
        // on the BST and store it in arr
        Inorder(root, arr);

        // Now, check if any triplet with given sum
        // exists in the BST or not
        for (int i = 0; i < arr.Count - 2; i++) {
            int l = i + 1;
            int r = arr.Count - 1;

            while (l < r) {
                
                if (arr[l] + arr[r] == sum - arr[i]) {
                    return true;
                }
                else if (arr[l] + arr[r] < sum - arr[i])
                    l++;
                else
                    r--;
            }
        }

        return false;
    }

    static void Main() {
      
        // creating the following BST 
        //      50 
        //    /     \ 
        //   30     70 
        //   / \   / \ 
        //  20 40 60 80 
        Node root = new Node(50);
        root.left = new Node(30);
        root.right = new Node(70);
        root.left.left = new Node(20);
        root.left.right = new Node(40);
        root.right.left = new Node(60);
        root.right.right = new Node(80);

        int sum = 120;

        if (CheckForTriplet(root, sum))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
// JavaScript program to check if a triplet with
// given target exists in the BST or not

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

// A utility function to do inorder traversal
// of the BST and store values in an array
function inorder(curr, arr) {
    if (curr !== null) {
        inorder(curr.left, arr);
        arr.push(curr.data);
        inorder(curr.right, arr);
    }
}

// Function to check if a triplet with given SUM
// exists in the BST or not
function checkForTriplet(root, sum) {

    // Array to store the inorder traversal
    // of the BST
    let arr = [];

    // Call inorder() to do the inorder
    // on the BST and store it in arr
    inorder(root, arr);

    // Now, check if any triplet with given sum
    // exists in the BST or not
    for (let i = 0; i < arr.length - 2; i++) {
        let l = i + 1;
        let r = arr.length - 1;

        while (l < r) {
            if (arr[l] + arr[r] === sum - arr[i]) {
                return true;
            }
            else if (arr[l] + arr[r] < sum - arr[i])
                l++;
            else
                r--;
        }
    }

    return false;
}

// creating the following BST 
//      50 
//    /     \ 
//   30     70 
//   / \   / \ 
//  20 40 60 80 
let root = new Node(50);
root.left = new Node(30);
root.right = new Node(70);
root.left.left = new Node(20);
root.left.right = new Node(40);
root.right.left = new Node(60);
root.right.right = new Node(80);

let sum = 120;

if (checkForTriplet(root, sum))
    console.log("true");
else
    console.log("false");

Output
true

Time Complexity: O(n^2), as we are using nested loops.
Auxiliary Space: O(n), where n is the number of nodes in the given bst.

Related article:

Comment