VOOZH about

URL: https://www.geeksforgeeks.org/dsa/total-number-of-possible-binary-search-trees-with-n-keys/

⇱ Total number of possible Binary Search Trees and Binary Trees with n keys - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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).

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! 


Output
42
5040

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

Comment