Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
String with maximum number of unique characters
Next article icon

Number of Unique BST with N Keys

Last Updated : 15 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an integer n, the task is to find the total number of unique BSTs that can be made using values from 1 to n. 

Examples: 

Input: n = 3 
Output: 5
Explanation: For n = 3, preorder traversal of Unique BSTs are:
1 2 3
1 3 2
2 1 3
3 1 2
3 2 1

236


Input: n = 2 
Output: 2
Explanation: For n = 2, preorder traversal of Unique BSTs are:
1 2
2 1

72

Approach:

A binary search tree (BST) maintains the property that elements are arranged based on their relative order. Let’s define C(n) as the number of unique BSTs that can be constructed with n nodes.

When considering all possible BSTs, each of the n nodes can serve as the root. For any selected root, the remaining n-1 nodes must be divided into two groups:

  • Nodes with keys smaller than the root’s key
  • Nodes with keys larger than the root’s key.

Assume we choose the node with the i-th key as the root. In this scenario, there will be i-1 nodes that are smaller and n-i nodes that are larger than the chosen root. This leads to dividing the problem of counting the total BSTs with the i-th key as the root into two subproblems:

  • Calculating the number of unique BSTs for the left subtree containing i-1 nodes, represented as C(i-1).
  • Calculating the number of unique BSTs for the right subtree containing n-i nodes, represented as C(n-i).

Since the left and right subtrees are constructed independently, we multiply these counts to get the total number of BSTs for the current configuration: C(i-1) * C(n-i).

To find the total number of BSTs with n nodes, we sum this product across all possible roots (i.e., from i = 1 to n). Therefore,

C(n) = Σ(i = 1 to n) C(i-1) * C(n-i).

This formula corresponds to the recurrence relation for the nth Catalan number. So this is how it is a classic application of Catalan number. We just need to find nth catalan number. First few catalan numbers are 1 1 2 5 14 42 132 429 1430 4862, … (considered from 0th number).

Formula of catalan number is (1 / n+1) * ( 2*nCn). Please refer to Applications of Catalan Numbers.

C++
// C++ code of finding Number of Unique // BST with N Keys   #include <iostream> using namespace std;  // Function to calculate the binomial // coefficient C(n, k) int binomialCoeff(int n, int k) {        	// C(n, k) is the same as C(n, n-k)     if (k > n - k) {         k = n - k;     }      int res = 1;        // Calculate the value of n! / (k! * (n-k)!)     for (int i = 0; i < k; ++i) {         res *= (n - i);         res /= (i + 1);     }      return res; }  // Function to find the nth Catalan number int numTrees(int n) {        // Calculate C(2n, n)     int c = binomialCoeff(2 * n, n);        	// Return the nth Catalan number     return c / (n + 1); }  int main() {        int n = 5;     cout << numTrees(n) << endl;     return 0; } 
Java
// Java program to find the number of unique // BSTs with N keys  class GfG {        // Function to calculate the binomial   	// coefficient C(n, k)     static int binomialCoeff(int n, int k) {                // C(n, k) is the same as C(n, n-k)         if (k > n - k) {             k = n - k;         }          int res = 1;                // Calculate the value of n! / (k! * (n-k)!)         for (int i = 0; i < k; ++i) {             res *= (n - i);             res /= (i + 1);         }          return res;     }      // Function to find the nth Catalan number     static int numTrees(int n) {                // Calculate C(2n, n)         int c = binomialCoeff(2 * n, n);          // Return the nth Catalan number         return c / (n + 1);     }      public static void main(String[] args) {         int n = 5;         System.out.println(numTrees(n));     } } 
Python
# Python program to find the number of unique  # BSTs with N keys  # Function to calculate the binomial coefficient C(n, k) def binomial_coeff(n, k):        # C(n, k) is the same as C(n, n-k)     if k > n - k:         k = n - k      res = 1          # Calculate the value of n! / (k! * (n-k)!)     for i in range(k):         res *= (n - i)         res //= (i + 1)      return res  # Function to find the nth Catalan number def numTrees(n):        # Calculate C(2n, n)     c = binomial_coeff(2 * n, n)      # Return the nth Catalan number     return c // (n + 1)  n = 5 print(numTrees(n)) 
C#
// C# program to find the number of unique // BSTs with N keys  using System;  class GfG {        // Function to calculate the binomial   	// coefficient C(n, k)     static int BinomialCoeff(int n, int k) {                // C(n, k) is the same as C(n, n-k)         if (k > n - k) {             k = n - k;         }          int res = 1;                // Calculate the value of n! / (k! * (n-k)!)         for (int i = 0; i < k; ++i) {             res *= (n - i);             res /= (i + 1);         }          return res;     }      // Function to find the nth Catalan   	// number     static int numTrees(int n) {                // Calculate C(2n, n)         int c = BinomialCoeff(2 * n, n);          // Return the nth Catalan number         return c / (n + 1);     }      static void Main() {         int n = 5;         Console.WriteLine(numTrees(n));     } } 
JavaScript
// JavaScript program to find the number of unique BSTs with // n keys  // Function to calculate the binomial coefficient C(n, k) function binomialCoeff(n, k) {      // C(n, k) is the same as C(n, n-k)     if (k > n - k) {         k = n - k;     }      let res = 1;          // Calculate the value of n! / (k! * (n-k)!)     for (let i = 0; i < k; i++) {         res *= (n - i);         res /= (i + 1);     }      return res; }  // Function to find the nth Catalan number function numTrees(n) {      // Calculate C(2n, n)     let c = binomialCoeff(2 * n, n);      // Return the nth Catalan number     return c / (n + 1); }  const n = 5; console.log(numTrees(n)); 

Output
42 

Time Complexity: O(n), where n is nth catalan number.
Auxiliary Space: O(1)



Next Article
String with maximum number of unique characters

A

Aashish Chauhan
Improve
Article Tags :
  • Advanced Data Structure
  • Binary Search Tree
  • DSA
  • Dynamic Programming
Practice Tags :
  • Advanced Data Structure
  • Binary Search Tree
  • Dynamic Programming

Similar Reads

  • Number of Unique BST with N Keys
    Given an integer n, the task is to find the total number of unique BSTs that can be made using values from 1 to n. Examples: Input: n = 3 Output: 5Explanation: For n = 3, preorder traversal of Unique BSTs are:1 2 31 3 22 1 33 1 23 2 1 Input: n = 2 Output: 2Explanation: For n = 2, preorder traversal
    6 min read
  • String with maximum number of unique characters
    Given an array of strings, the task is to print the string with the maximum number of unique characters. Note: Strings consists of lowercase characters.If multiple strings exists, then print any one of them.Examples: Input: arr[] = ["abc", "geeksforgeeks", "gfg", "code"]Output: "geeksforgeeks" Expla
    5 min read
  • Count of unique digits in a given number N
    Given a number N, the task is to count the number of unique digits in the given number. Examples: Input: N = 22342 Output: 2 Explanation:The digits 3 and 4 occurs only once. Hence, the output is 2. Input: N = 99677 Output: 1Explanation:The digit 6 occurs only once. Hence, the output is 1. Naive Appr
    6 min read
  • Print all numbers less than N with at-most 2 unique digits
    Given a number N(less than 10^9). The task is to print all the numbers less than N which are having a maximum of 2 unique digits. Note: Number such as 100, 111, 101 are valid as the number of unique digits are at most 2 but 123 is invalid as it has 3 unique digits.Examples: Input: N = 12 Output: The
    6 min read
  • Numbers having Unique (or Distinct) digits
    Given a range, print all numbers having unique digits. Examples : Input : 10 20Output : 10 12 13 14 15 16 17 18 19 20 (Except 11)Input : 1 10Output : 1 2 3 4 5 6 7 8 9 10Approach: As the problem is pretty simple, the only thing to be done is :-1- Find the digits one by one and keep marking visited d
    11 min read
  • Print first n numbers with exactly two set bits
    Given a number n, print first n positive integers with exactly two set bits in their binary representation.Examples : Input: n = 3Output: 3 5 6The first 3 numbers with two set bits are 3 (0011),5 (0101) and 6 (0110)Input: n = 5Output: 3 5 6 9 10 12A Simple Solution is to consider all positive intege
    11 min read
  • Unique Numbers ||
    Given an array arr[] containing 2*n + 2 positive numbers, out of which 2*n numbers exist in pairs whereas the other two number occur exactly once and are distinct. The task is to find the other two numbers. Note: Return the numbers in increasing order. Example: Input: arr[] = [1, 2, 3, 2, 1, 4]Outpu
    15 min read
  • Count Number of Nodes With Value One in Undirected Tree
    Given an undirected connected tree with n nodes labeled from 1 to n, and an integer array of queries[]. Initially, all nodes have a value of 0. For each query in the array, you need to flip the values of all nodes in the subtree of the node with the corresponding label. The parent of a node with lab
    8 min read
  • Longest substring with k unique characters
    Given a string you need to print longest possible substring that has exactly k unique characters. If there is more than one substring of longest possible length, then print any one of them. Note:- Source(Google Interview Question). Examples: Input: Str = "aabbcc", k = 1Output: 2Explanation: Max subs
    13 min read
  • Number of unique triplets whose XOR is zero
    Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15};Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences