Given a binary search tree containing N distinct nodes and a value K. The task is to count pairs in the given binary search tree whose sum is greater than the given value K.
Examples:
Input:
5
/ \
3 7
/ \ / \
2 4 6 8
k = 11
Output: 6
Explanation:
There are 6 pairs which are (4, 8), (5, 7), (5, 8), (6, 7), (6, 8) and (7, 8).
Input:
8
/ \
3 9
\ / \
5 6 18
k = 23
Output: 3
Explanation:
There are 3 pairs which are (6, 18), (8, 18) and (9, 18).
Naive Approach:
To solve the problem mentioned above we have to store inorder traversal of BST in an array then run two loops to generate all pairs and one by one check if the current pair’s sum is greater than k or not.
Below is the implementation of the approach:
// C++ program to Count // pair in BST whose Sum // is greater than K #include <bits/stdc++.h> using namespace std;
// Structure of each node of BST struct node {
int key;
struct node *left, *right;
}; // Function to create a new BST node node* newNode( int item)
{ node* temp = new node();
temp->key = item;
temp->left = temp->right = NULL;
return temp;
} /* Function to insert a new node with given key in BST */ struct node* insert( struct node* node, int key)
{ // check if the tree is empty
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
/* return the (unchanged) node pointer */
return node;
} // Function to return the size of the tree int sizeOfTree(node* root)
{ if (root == NULL) {
return 0;
}
// Calculate left size recursively
int left = sizeOfTree(root->left);
// Calculate right size recursively
int right = sizeOfTree(root->right);
// Return total size recursively
return (left + right + 1);
} // Function to store inorder traversal of BST void storeInorder(node* root, int inOrder[], int & index)
{ // Base condition
if (root == NULL) {
return ;
}
// Left recursive call
storeInorder(root->left, inOrder, index);
// Store elements in inorder array
inOrder[index++] = root->key;
// Right recursive call
storeInorder(root->right, inOrder, index);
} // function to count the pair of BST // whose sum is greater than k int countPairUtil( int inOrder[], int j, int k)
{ int pair = 0;
for ( int x = 0; x < j; x++) {
for ( int y = x + 1; y <= j; y++) {
int sum = inOrder[x] + inOrder[y];
if (sum > k)
pair++;
}
}
// Return number of total pair
return pair;
} // Function to count the // pair of BST whose sum is // greater than k int countPair(node* root, int k)
{ // Store the size of BST
int numNode = sizeOfTree(root);
// Auxiliary array for storing
// the inorder traversal of BST
int inOrder[numNode + 1];
int index = 0;
storeInorder(root, inOrder, index);
// Function call to count the pair
return countPairUtil(inOrder, index - 1, k);
} // Driver code int main()
{ // create tree
struct node* root = NULL;
root = insert(root, 5);
insert(root, 3);
insert(root, 2);
insert(root, 4);
insert(root, 7);
insert(root, 6);
insert(root, 8);
int k = 11;
// Print the number of pair
cout << countPair(root, k);
return 0;
} |
// Java program to count // pair in BST whose Sum // is greater than K import java.util.*;
class Node {
int key;
Node left, right;
Node( int data)
{
key = data;
left = right = null ;
}
} class BST {
Node root;
BST() { root = null ; }
// Function to insert a new node
public Node insert(Node node, int key)
{
if (node == null )
return new Node(key);
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
return node;
}
// Function to return the size of the tree
public int sizeOfTree(Node root)
{
if (root == null )
return 0 ;
// Calculate left size recursively
int left = sizeOfTree(root.left);
// Calculate right size recursively
int right = sizeOfTree(root.right);
// Return total size recursively
return (left + right + 1 );
}
// Function to store inorder traversal of BST
public void storeInorder(Node root, int [] inOrder,
int [] index)
{
if (root == null )
return ;
// Left recursive call
storeInorder(root.left, inOrder, index);
// Store elements in inorder array
inOrder[index[ 0 ]++] = root.key;
// Right recursive call
storeInorder(root.right, inOrder, index);
}
// function to count the pair of BST
// whose sum is greater than k
public int countPairUtil( int [] inOrder, int j, int k)
{
int pair = 0 ;
for ( int x = 0 ; x < j; x++) {
for ( int y = x + 1 ; y <= j; y++) {
int sum = inOrder[x] + inOrder[y];
if (sum > k)
pair++;
}
}
// Return number of total pair
return pair;
}
// Function to count the
// pair of BST whose sum is
// greater than k
public int countPair(Node root, int k)
{
// Store the size of BST
int numNode = sizeOfTree(root);
// Auxiliary array for storing
// the inorder traversal of BST
int [] inOrder = new int [numNode + 1 ];
int [] index = { 0 };
storeInorder(root, inOrder, index);
// Function call to count the pair
return countPairUtil(inOrder, index[ 0 ] - 1 , k);
}
} // Driver code public class GFG {
public static void main(String[] args)
{
// create tree
BST bst = new BST();
bst.root = bst.insert(bst.root, 5 );
bst.insert(bst.root, 3 );
bst.insert(bst.root, 2 );
bst.insert(bst.root, 4 );
bst.insert(bst.root, 7 );
bst.insert(bst.root, 6 );
bst.insert(bst.root, 8 );
int k = 11 ;
// Print the number of pair
System.out.print(bst.countPair(bst.root, k));
}
} |
# Python3 program to count pair in # BST whose sum is greater than K index = 0
# Structure of each node of BST class newNode:
# Function to create a new BST node
def __init__( self , item):
self .key = item
self .left = None
self .right = None
# Function to insert a new # node with given key in BST def insert(node, key):
# Check if the tree is empty
if (node = = None ):
return newNode(key)
if (key < node.key):
node.left = insert(node.left, key)
elif (key > node.key):
node.right = insert(node.right, key)
# Return the (unchanged) node pointer
return node
# Function to return the size of the tree def sizeOfTree(root):
if (root = = None ):
return 0
# Calculate left size recursively
left = sizeOfTree(root.left)
# Calculate right size recursively
right = sizeOfTree(root.right)
# Return total size recursively
return (left + right + 1 )
# Function to store inorder traversal of BST def storeInorder(root, inOrder):
global index
# Base condition
if (root = = None ):
return
# Left recursive call
storeInorder(root.left, inOrder)
# Store elements in inorder array
inOrder[index] = root.key
index + = 1
# Right recursive call
storeInorder(root.right, inOrder)
# Function to count the pair of BST # whose sum is greater than k def countPairUtil(inOrder, j, k):
pair = 0
for x in range (j):
for y in range (x + 1 , j + 1 ):
sum = inOrder[x] + inOrder[y]
if sum > k:
pair + = 1
# Return number of total pair
return pair
# Function to count the # pair of BST whose sum is # greater than k def countPair(root, k):
global index
# Store the size of BST
numNode = sizeOfTree(root)
# Auxiliary array for storing
# the inorder traversal of BST
inOrder = [ 0 for i in range (numNode + 1 )]
storeInorder(root, inOrder)
# Function call to count the pair
return countPairUtil(inOrder, index - 1 , k)
# Driver code if __name__ = = '__main__' :
# Create tree
root = None
root = insert(root, 5 )
insert(root, 3 )
insert(root, 2 )
insert(root, 4 )
insert(root, 7 )
insert(root, 6 )
insert(root, 8 )
k = 11
# Print the number of pair
print (countPair(root, k))
|
using System;
// Structure of each node of BST public class Node
{ public int Key;
public Node Left, Right;
public Node( int item)
{
Key = item;
Left = Right = null ;
}
} class GFG
{ // Function to insert a new node
// with given key in BST
public static Node Insert(Node root, int key)
{
if (root == null )
return new Node(key);
if (key < root.Key)
root.Left = Insert(root.Left, key);
else if (key > root.Key)
root.Right = Insert(root.Right, key);
return root;
}
// Function to return the size of the tree
public static int SizeOfTree(Node root)
{
if (root == null )
return 0;
int left = SizeOfTree(root.Left);
int right = SizeOfTree(root.Right);
return left + right + 1;
}
// Function to store inorder traversal of BST
public static void StoreInorder(Node root, int [] inOrder, ref int index)
{
if (root == null )
return ;
StoreInorder(root.Left, inOrder, ref index);
inOrder[index++] = root.Key;
StoreInorder(root.Right, inOrder, ref index);
}
// Function to count the pairs of BST whose s
// um is greater than k
public static int CountPairUtil( int [] inOrder, int j, int k)
{
int pair = 0;
for ( int x = 0; x < j; x++)
{
for ( int y = x + 1; y <= j; y++)
{
int sum = inOrder[x] + inOrder[y];
if (sum > k)
pair++;
}
}
return pair;
}
// Function to count the pairs of
// BST whose sum is greater than k
public static int CountPair(Node root, int k)
{
int numNode = SizeOfTree(root);
int [] inOrder = new int [numNode + 1];
int index = 0;
StoreInorder(root, inOrder, ref index);
return CountPairUtil(inOrder, index - 1, k);
}
// Driver code
static void Main( string [] args)
{
Node root = null ;
root = Insert(root, 5);
Insert(root, 3);
Insert(root, 2);
Insert(root, 4);
Insert(root, 7);
Insert(root, 6);
Insert(root, 8);
int k = 11;
Console.WriteLine(CountPair(root, k));
}
} |
let index = 0; class Node { constructor(item) {
this .key = item;
this .left = null ;
this .right = null ;
}
} function insert(node, key) {
if (node == null ) {
return new Node(key);
}
if (key < node.key) {
node.left = insert(node.left, key);
} else if (key > node.key) {
node.right = insert(node.right, key);
}
return node;
} function sizeOfTree(root) {
if (root == null ) {
return 0;
}
let left = sizeOfTree(root.left);
let right = sizeOfTree(root.right);
return left + right + 1;
} function storeInorder(root, inOrder) {
if (root == null ) {
return ;
}
storeInorder(root.left, inOrder);
inOrder[index] = root.key;
index++;
storeInorder(root.right, inOrder);
} function countPairUtil(inOrder, j, k) {
let pair = 0;
for (let x = 0; x < j; x++) {
for (let y = x + 1; y < j + 1; y++) {
let sum = inOrder[x] + inOrder[y];
if (sum > k) {
pair++;
}
}
}
return pair;
} function countPair(root, k) {
let numNode = sizeOfTree(root);
let inOrder = new Array(numNode + 1).fill(0);
storeInorder(root, inOrder);
return countPairUtil(inOrder, index - 1, k);
} let root = null ;
root = insert(root, 5); insert(root, 3); insert(root, 2); insert(root, 4); insert(root, 7); insert(root, 6); insert(root, 8); let k = 11; console.log(countPair(root, k)); |
6
Time Complexity: O(N*N) as two nested loop is there in countPairUtil.
Space Complexity: O(N) because of arrays been created and the recursion stack also.
Efficient Approach:
The above method can be optimized if we store the inorder traversal of BST in an array and take the initial and last index of the array in l and r variable to find the total pair in the inorder array. Initially assign l as 0 and r as n-1. Consider a variable and initialize it to zero. This variable result will be our final answer. Now iterate until l < r and if the current left and current right have a sum greater than K, all elements from l+1 to r form a pair with it otherwise it doesn’t, therefore, increment current left. Finally, return the result.
Below is the implementation of the above approach:
// C++ program to Count // pair in BST whose Sum // is greater than K #include <bits/stdc++.h> using namespace std;
// Structure of each node of BST struct node {
int key;
struct node *left, *right;
}; // Function to create a new BST node node* newNode( int item)
{ node* temp = new node();
temp->key = item;
temp->left = temp->right = NULL;
return temp;
} /* Function to insert a new node with given key in BST */ struct node* insert( struct node* node, int key)
{ // check if the tree is empty
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
/* return the (unchanged) node pointer */
return node;
} // Function to return the size of the tree int sizeOfTree(node* root)
{ if (root == NULL) {
return 0;
}
// Calculate left size recursively
int left = sizeOfTree(root->left);
// Calculate right size recursively
int right = sizeOfTree(root->right);
// Return total size recursively
return (left + right + 1);
} // Function to store inorder traversal of BST void storeInorder(node* root, int inOrder[],
int & index)
{ // Base condition
if (root == NULL) {
return ;
}
// Left recursive call
storeInorder(root->left, inOrder, index);
// Store elements in inorder array
inOrder[index++] = root->key;
// Right recursive call
storeInorder(root->right, inOrder, index);
} // function to count the pair of BST // whose sum is greater than k int countPairUtil( int inOrder[], int j, int k)
{ int i = 0;
int pair = 0;
while (i < j) {
// check if sum of value at index
// i and j is greater than k
if (inOrder[i] + inOrder[j] > k) {
pair += j - i;
j--;
}
else {
i++;
}
}
// Return number of total pair
return pair;
} // Function to count the // pair of BST whose sum is // greater than k int countPair(node* root, int k)
{ // Store the size of BST
int numNode = sizeOfTree(root);
// Auxiliary array for storing
// the inorder traversal of BST
int inOrder[numNode + 1];
int index = 0;
storeInorder(root, inOrder, index);
// Function call to count the pair
return countPairUtil(inOrder, index - 1, k);
} // Driver code int main()
{ // create tree
struct node* root = NULL;
root = insert(root, 5);
insert(root, 3);
insert(root, 2);
insert(root, 4);
insert(root, 7);
insert(root, 6);
insert(root, 8);
int k = 11;
// Print the number of pair
cout << countPair(root, k);
return 0;
} |
// Java program to Count // pair in BST whose Sum // is greater than K class GFG{
// Structure of each node of BST static class node {
int key;
node left, right;
}; static int index;
// Function to create a new BST node static node newNode( int item)
{ node temp = new node();
temp.key = item;
temp.left = temp.right = null ;
return temp;
} /* Function to insert a new node with given key in BST */ static node insert(node node, int key)
{ // check if the tree is empty
if (node == null )
return newNode(key);
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
/* return the (unchanged) node pointer */
return node;
} // Function to return the size of the tree static int sizeOfTree(node root)
{ if (root == null ) {
return 0 ;
}
// Calculate left size recursively
int left = sizeOfTree(root.left);
// Calculate right size recursively
int right = sizeOfTree(root.right);
// Return total size recursively
return (left + right + 1 );
} // Function to store inorder traversal of BST static void storeInorder(node root, int inOrder[])
{ // Base condition
if (root == null ) {
return ;
}
// Left recursive call
storeInorder(root.left, inOrder);
// Store elements in inorder array
inOrder[index++] = root.key;
// Right recursive call
storeInorder(root.right, inOrder);
} // function to count the pair of BST // whose sum is greater than k static int countPairUtil( int inOrder[], int j, int k)
{ int i = 0 ;
int pair = 0 ;
while (i < j) {
// check if sum of value at index
// i and j is greater than k
if (inOrder[i] + inOrder[j] > k) {
pair += j - i;
j--;
}
else {
i++;
}
}
// Return number of total pair
return pair;
} // Function to count the // pair of BST whose sum is // greater than k static int countPair(node root, int k)
{ // Store the size of BST
int numNode = sizeOfTree(root);
// Auxiliary array for storing
// the inorder traversal of BST
int []inOrder = new int [numNode + 1 ];
index = 0 ;
storeInorder(root, inOrder);
// Function call to count the pair
return countPairUtil(inOrder, index - 1 , k);
} // Driver code public static void main(String[] args)
{ // create tree
node root = null ;
root = insert(root, 5 );
insert(root, 3 );
insert(root, 2 );
insert(root, 4 );
insert(root, 7 );
insert(root, 6 );
insert(root, 8 );
int k = 11 ;
// Print the number of pair
System.out.print(countPair(root, k));
} } // This code is contributed by Princi Singh |
# Python3 program to count pair in # BST whose sum is greater than K index = 0
# Structure of each node of BST class newNode:
# Function to create a new BST node
def __init__( self , item):
self .key = item
self .left = None
self .right = None
# Function to insert a new # node with given key in BST def insert(node, key):
# Check if the tree is empty
if (node = = None ):
return newNode(key)
if (key < node.key):
node.left = insert(node.left, key)
elif (key > node.key):
node.right = insert(node.right, key)
# Return the (unchanged) node pointer
return node
# Function to return the size of the tree def sizeOfTree(root):
if (root = = None ):
return 0
# Calculate left size recursively
left = sizeOfTree(root.left)
# Calculate right size recursively
right = sizeOfTree(root.right)
# Return total size recursively
return (left + right + 1 )
# Function to store inorder traversal of BST def storeInorder(root, inOrder):
global index
# Base condition
if (root = = None ):
return
# Left recursive call
storeInorder(root.left, inOrder)
# Store elements in inorder array
inOrder[index] = root.key
index + = 1
# Right recursive call
storeInorder(root.right, inOrder)
# Function to count the pair of BST # whose sum is greater than k def countPairUtil(inOrder, j, k):
i = 0
pair = 0
while (i < j):
# Check if sum of value at index
# i and j is greater than k
if (inOrder[i] + inOrder[j] > k):
pair + = j - i
j - = 1
else :
i + = 1
# Return number of total pair
return pair
# Function to count the # pair of BST whose sum is # greater than k def countPair(root, k):
global index
# Store the size of BST
numNode = sizeOfTree(root)
# Auxiliary array for storing
# the inorder traversal of BST
inOrder = [ 0 for i in range (numNode + 1 )]
storeInorder(root, inOrder)
# Function call to count the pair
return countPairUtil(inOrder, index - 1 , k)
# Driver code if __name__ = = '__main__' :
# Create tree
root = None
root = insert(root, 5 )
insert(root, 3 )
insert(root, 2 )
insert(root, 4 )
insert(root, 7 )
insert(root, 6 )
insert(root, 8 )
k = 11
# Print the number of pair
print (countPair(root, k))
# This code is contributed by ipg2016107 |
// C# program to Count // pair in BST whose Sum // is greater than K using System;
class GFG{
// Structure of each node of BST class node {
public int key;
public node left, right;
}; static int index;
// Function to create a new BST node static node newNode( int item)
{ node temp = new node();
temp.key = item;
temp.left = temp.right = null ;
return temp;
} /* Function to insert a new node with given key in BST */ static node insert(node node, int key)
{ // check if the tree is empty
if (node == null )
return newNode(key);
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
/* return the (unchanged) node pointer */
return node;
} // Function to return the size of the tree static int sizeOfTree(node root)
{ if (root == null ) {
return 0;
}
// Calculate left size recursively
int left = sizeOfTree(root.left);
// Calculate right size recursively
int right = sizeOfTree(root.right);
// Return total size recursively
return (left + right + 1);
} // Function to store inorder traversal of BST static void storeInorder(node root, int []inOrder)
{ // Base condition
if (root == null ) {
return ;
}
// Left recursive call
storeInorder(root.left, inOrder);
// Store elements in inorder array
inOrder[index++] = root.key;
// Right recursive call
storeInorder(root.right, inOrder);
} // function to count the pair of BST // whose sum is greater than k static int countPairUtil( int []
inOrder, int j, int k)
{ int i = 0;
int pair = 0;
while (i < j) {
// check if sum of value at index
// i and j is greater than k
if (inOrder[i] + inOrder[j] > k) {
pair += j - i;
j--;
}
else {
i++;
}
}
// Return number of total pair
return pair;
} // Function to count the // pair of BST whose sum is // greater than k static int countPair(node root, int k)
{ // Store the size of BST
int numNode = sizeOfTree(root);
// Auxiliary array for storing
// the inorder traversal of BST
int []inOrder = new int [numNode + 1];
index = 0;
storeInorder(root, inOrder);
// Function call to count the pair
return countPairUtil(inOrder, index - 1, k);
} // Driver code public static void Main(String[] args)
{ // create tree
node root = null ;
root = insert(root, 5);
insert(root, 3);
insert(root, 2);
insert(root, 4);
insert(root, 7);
insert(root, 6);
insert(root, 8);
int k = 11;
// Print the number of pair
Console.Write(countPair(root, k));
} } // This code is contributed by Rajput-Ji |
<script> // JavaScript program to Count
// pair in BST whose Sum
// is greater than K
// Structure of each node of BST
class node {
constructor(item) {
this .left = null ;
this .right = null ;
this .key = item;
}
}
let index;
// Function to create a new BST node
function newNode(item)
{
let temp = new node(item);
return temp;
}
/* Function to insert a new
node with given key in BST */
function insert(node, key)
{
// check if the tree is empty
if (node == null )
return newNode(key);
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
/* return the (unchanged) node pointer */
return node;
}
// Function to return the size of the tree
function sizeOfTree(root)
{
if (root == null ) {
return 0;
}
// Calculate left size recursively
let left = sizeOfTree(root.left);
// Calculate right size recursively
let right = sizeOfTree(root.right);
// Return total size recursively
return (left + right + 1);
}
// Function to store inorder traversal of BST
function storeInorder(root, inOrder)
{
// Base condition
if (root == null ) {
return ;
}
// Left recursive call
storeInorder(root.left, inOrder);
// Store elements in inorder array
inOrder[index++] = root.key;
// Right recursive call
storeInorder(root.right, inOrder);
}
// function to count the pair of BST
// whose sum is greater than k
function countPairUtil(inOrder, j, k)
{
let i = 0;
let pair = 0;
while (i < j) {
// check if sum of value at index
// i and j is greater than k
if (inOrder[i] + inOrder[j] > k) {
pair += j - i;
j--;
}
else {
i++;
}
}
// Return number of total pair
return pair;
}
// Function to count the
// pair of BST whose sum is
// greater than k
function countPair(root, k)
{
// Store the size of BST
let numNode = sizeOfTree(root);
// Auxiliary array for storing
// the inorder traversal of BST
let inOrder = new Array(numNode + 1);
index = 0;
storeInorder(root, inOrder);
// Function call to count the pair
return countPairUtil(inOrder, index - 1, k);
}
// create tree
let root = null ;
root = insert(root, 5);
insert(root, 3);
insert(root, 2);
insert(root, 4);
insert(root, 7);
insert(root, 6);
insert(root, 8);
let k = 11;
// Print the number of pair
document.write(countPair(root, k));
</script> |
6