Count of BSTs with N nodes having height at least K
Last Updated :
20 Jul, 2021
Given two positive integers N and K, the task is to find the number of binary search trees (BST) with N nodes of height greater than or equal to K.
Note: Here height refers to the maximum depth of the BST.
Examples:
Input: N = 3, K = 3
Output: 4
Explanation:
There are 4 possible binary search trees with height greater than or equal to K.
1 1 3 3
\ \ / /
2 3 2 1
\ | / \
3 2 1 2
Input: N = 4, K = 2
Output: 14
Approach: This problem can be solved using recursion. Follow the steps below to solve the problem:
- Base Case: if N is equal to 1 then return 1.
- Initialize a variable countBsts as 0 to store the number of valid BSTs.
- Iterate in the range [1, N] using the variable i:
- If i-1 and N-i is greater than equal to K, then:
- Recursively call the function for left subtree, with nodes as i – 1 and height as K – 1 which will find the number of ways to create left subtree.
- Recursively call the function for right subtree with nodes as N – i and height as K – 1 which will find the number of ways to create right subtree.
- Add the result in countBsts.
- After completing the above steps, print the countBsts.
C++
#include <bits/stdc++.h>
using namespace std;
int numOfBst( int n, int k)
{
if (n <= 1) {
return 1;
}
int countBsts = 0;
for ( int i = 1; i <= n; i++) {
if (i - 1 >= k or n - i >= k)
countBsts
+= numOfBst(i - 1, k - 1)
* numOfBst(n - i, k - 1);
}
return countBsts;
}
int main()
{
int n = 4;
int k = 2;
cout << numOfBst(n, k - 1) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int numOfBst( int n, int k)
{
if (n <= 1 ) {
return 1 ;
}
int countBsts = 0 ;
for ( int i = 1 ; i <= n; i++)
{
if (i - 1 >= k || n - i >= k)
countBsts += numOfBst(i - 1 , k - 1 )
* numOfBst(n - i, k - 1 );
}
return countBsts;
}
public static void main(String[] args)
{
int n = 4 ;
int k = 2 ;
System.out.println(numOfBst(n, k - 1 ));
}
}
|
Python3
def numOfBst(n, k):
if (n < = 1 ):
return 1
countBsts = 0
for i in range ( 1 , n + 1 , 1 ):
if (i - 1 > = k or n - i > = k):
countBsts + = numOfBst(i - 1 , k - 1 ) * numOfBst(n - i, k - 1 )
return countBsts
if __name__ = = '__main__' :
n = 4
k = 2
print (numOfBst(n, k - 1 ))
|
C#
using System;
class GFG {
static int numOfBst( int n, int k)
{
if (n <= 1) {
return 1;
}
int countBsts = 0;
for ( int i = 1; i <= n; i++)
{
if (i - 1 >= k || n - i >= k)
countBsts += numOfBst(i - 1, k - 1)
* numOfBst(n - i, k - 1);
}
return countBsts;
}
static void Main()
{
int n = 4;
int k = 2;
Console.WriteLine(numOfBst(n, k - 1));
}
}
|
Javascript
<script>
function numOfBst(n, k) {
if (n <= 1) {
return 1;
}
let countBsts = 0;
for (let i = 1; i <= n; i++) {
if (i - 1 >= k || n - i >= k)
countBsts
+= numOfBst(i - 1, k - 1)
* numOfBst(n - i, k - 1);
}
return countBsts;
}
let n = 4;
let k = 2;
document.write(numOfBst(n, k - 1) + "<br>" );
</script>
|
Time Complexity: O(2n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...