Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Total number of possible Binary Search Trees and Binary Trees with n keys
Next article icon

Total number of possible Binary Search Trees and Binary Trees with n keys

Last Updated : 11 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Examples:

Input: n = 3 
Output: BST = 5
BT = 30
Explanation: For n = 3, Total number of binary search tree will be 5 and total Binary tree will b 30.

Input: n = 5 
Output: BST = 42
BT = 5040
Explanation: For n = 5, Total number of binary search tree will be 42 and total Binary tree will b 5040.

Approach:

1. Unique Binary Search Trees (BSTs):

First let's see how we find Total number of binary search tree with n nodes. 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. This is given by the following recursive formula:

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

This formula corresponds to the recurrence relation for the nth Catalan number. Please refer to Number of Unique BST with N Keys for better understanding and proof. 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.

2. Unique Binary Trees (General Binary Trees):

For general binary trees, the nodes do not have to follow the Binary Search Tree property. The total number of unique binary trees is calculated as: Total Binary Trees = countBST(n) * n! 

C++
// C++ code of finding Number of Unique // BST and BT 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 numBST(int n) {        // Calculate C(2n, n)     int c = binomialCoeff(2 * n, n);        	// Return the nth Catalan number     return c / (n + 1); }  // Function to find total binary tree int numBT(int n) {        int fact = 1;      	// Calculating factorial   	for(int i = 1; i <= n; i++) {      	fact = fact * i;      }      	// Total binary tree = Tatal binary search tree * n!   	return numBST(n) * fact; }  int main() {        int n = 5;     cout << numBST(n) << endl;  	cout << numBT(n) << endl;     return 0; } 
Java
// Java code of finding Number of Unique // BST and BT 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 numBST(int n) {                // Calculate C(2n, n)         int c = binomialCoeff(2 * n, n);          // Return the nth Catalan number         return c / (n + 1);     }      // Function to find total binary tree     static int numBT(int n) {         int fact = 1;          // Calculating factorial         for (int i = 1; i <= n; i++) {             fact = fact * i;         }          // Total binary tree = Total binary search tree * n!         return numBST(n) * fact;     }      public static void main(String[] args) {         int n = 5;         System.out.println(numBST(n));         System.out.println(numBT(n));     } } 
Python
# Python code of finding Number of Unique # BST and BT with N Keys  # Function to calculate the binomial coefficient C(n, k) def binomialCoeff(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 numBST(n):        # Calculate C(2n, n)     c = binomialCoeff(2 * n, n)      # Return the nth Catalan number     return c // (n + 1)  # Function to find total binary tree def numBT(n):     fact = 1      # Calculating factorial     for i in range(1, n + 1):         fact *= i      # Total binary tree = Total binary search tree * n!     return numBST(n) * fact  n = 5 print(numBST(n)) print(numBT(n)) 
C#
// C# code of finding Number of Unique // BST and BT 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 numBST(int n) {          // Calculate C(2n, n)         int c = binomialCoeff(2 * n, n);          // Return the nth Catalan number         return c / (n + 1);     }      // Function to find total binary tree     static int numBT(int n) {         int fact = 1;          // Calculating factorial         for (int i = 1; i <= n; i++) {             fact = fact * i;         }          // Total binary tree = Total binary        	// search tree * n!         return numBST(n) * fact;     }      static void Main() {         int n = 5;         Console.WriteLine(numBST(n));         Console.WriteLine(numBT(n));     } } 
JavaScript
// JavaScript code of finding Number of Unique // BST and BT 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 numBST(n) {      // Calculate C(2n, n)     let c = binomialCoeff(2 * n, n);      // Return the nth Catalan number     return c / (n + 1); }  // Function to find total binary tree function numBT(n) {     let fact = 1;      // Calculating factorial     for (let i = 1; i <= n; i++) {         fact *= i;     }      // Total binary tree = Total binary search tree * n!     return numBST(n) * fact; }  let n = 5; console.log(numBST(n)); console.log(numBT(n)); 

Output
42 5040 

Time Complexity: O(n), where n is total number of node
Auxiliary Space: O(1)


Next Article
Total number of possible Binary Search Trees and Binary Trees with n keys

K

kartik
Improve
Article Tags :
  • Dynamic Programming
  • Binary Search Tree
  • DSA
  • Amazon
  • Samsung
  • Twitter
  • catalan
Practice Tags :
  • Amazon
  • Samsung
  • Twitter
  • Binary Search Tree
  • Dynamic Programming

Similar Reads

    Count the Number of Binary Search Trees present in a Binary Tree
    Given a binary tree, the task is to count the number of Binary Search Trees present in it. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 4Here each leaf node represents a binary search tree and there are total 4 nodes. Input: 11 / \ 8 10 / / \ 5 9 8 / \ 4 6 Output: 6 Sub-tree rooted under node
    10 min read
    Total number of possible Binary Search Trees using Catalan Number
    Given an integer N, the task is to count the number of possible Binary Search Trees with N keys. Examples: Input: N = 2 Output: 2 For N = 2, there are 2 unique BSTs 1 2 \ / 2 1 Input: N = 9 Output: 4862 Approach: The number of binary search trees that will be formed with N keys can be calculated by
    13 min read
    Number of pairs with a given sum in a Binary Search Tree
    Given a Binary Search Tree, and a number X. The task is to find the number of distinct pairs of distinct nodes in BST with a sum equal to X. No two nodes have the same values. Examples: Input : X = 5 5 / \ 3 7 / \ / \ 2 4 6 8 Output : 1 {2, 3} is the only possible pair. Thus, the answer is equal to
    9 min read
    Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
    In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delet
    4 min read
    Find the minimum Sub-tree with target sum in a Binary search tree
    Given a binary tree and a target, find the number of nodes in the minimum sub-tree with the given sum equal to the target which is also a binary search tree. Examples: Input: 13 / \ 5 23 / \ / \ N 17 N N / 16Target: 38Output: 3Explanation: 5, 17, 16 is the smallest subtree with length 3. Input: 7 /
    9 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