Construct all possible BSTs for keys 1 to N

27 Jun, 2022
In this article, first count of possible BST (Binary Search Trees)s is discussed, then the construction of all possible BSTs.
How many structurally unique BSTs for keys from 1..N? 
For example, for N = 2, there are 2 unique BSTs
     1               2  
      \            /
       2         1 

For N = 3, there are 5 possible BSTs
  1              3        3         2      1
    \           /        /        /  \      \
     3        2         1        1    3      2
    /       /            \                    \
   2      1               2                    3
We strongly recommend you to minimize your browser and try this yourself first.We know that all node in left subtree are smaller than root and in right subtree are larger than root so if we have ith number as root, all numbers from 1 to i-1 will be in left subtree and i+1 to N will be in right subtree. If 1 to i-1 can form x different trees and i+1 to N can from y different trees then we will have x*y total trees when ith number is root and we also have N choices for root also so we can simply iterate from 1 to N for root and another loop for left and right subtree. If we take a closer look, we can notice that the count is basically n’th Catalan number. We have discussed different approaches to find n’th Catalan number here. 
How to construct all BST for keys 1..N? The idea is to maintain a list of roots of all BSTs. Recursively construct all possible left and right subtrees. Create a tree for every pair of left and right subtree and add the tree to list. Below is detailed algorithm. 
Initialize list of BSTs as empty.  For every number i where i varies from 1 to N, do followingCreate a new node with key as ‘i’, let this node be ‘node’Recursively construct list of all left subtrees.Recursively construct list of all right subtrees.Iterate for all left subtreesFor current leftsubtree, iterate for all right subtreesAdd current left and right subtrees to ‘node’ and addnode’ to list.
Initialize list of BSTs as empty.  
For every number i where i varies from 1 to N, do followingCreate a new node with key as ‘i’, let this node be ‘node’Recursively construct list of all left subtrees.Recursively construct list of all right subtrees.
Create a new node with key as ‘i’, let this node be ‘node’
Recursively construct list of all left subtrees.
Recursively construct list of all right subtrees.
Iterate for all left subtreesFor current leftsubtree, iterate for all right subtreesAdd current left and right subtrees to ‘node’ and addnode’ to list.
For current leftsubtree, iterate for all right subtrees
Add current left and right subtrees to ‘node’ and add
node’ to list.
Below is the implementation of the above idea. 
C++
Java
Python3
C#
Javascript
// A C++ program to construct all unique BSTs for keys from 1 to n#include <bits/stdc++.h>using namespace std; //  node structurestruct node{    int key;    struct node *left, *right;}; // A utility function to create a new BST nodestruct node *newNode(int item){    struct node *temp =  new node;    temp->key = item;    temp->left = temp->right = NULL;    return temp;} // A utility function to do preorder traversal of BSTvoid preorder(struct node *root){    if (root != NULL)    {        cout << root->key << " ";        preorder(root->left);        preorder(root->right);    }} //  function for constructing treesvector<struct node *> constructTrees(int start, int end){    vector<struct node *> list;     /*  if start > end   then subtree will be empty so returning NULL        in the list */    if (start > end)    {        list.push_back(NULL);        return list;    }     /*  iterating through all values from start to end  for constructing\        left and right subtree recursively  */    for (int i = start; i <= end; i++)    {        /*  constructing left subtree   */        vector<struct node *> leftSubtree  = constructTrees(start, i - 1);         /*  constructing right subtree  */        vector<struct node *> rightSubtree = constructTrees(i + 1, end);         /*  now looping through all left and right subtrees and connecting            them to ith root  below  */        for (int j = 0; j < leftSubtree.size(); j++)        {            struct node* left = leftSubtree[j];            for (int k = 0; k < rightSubtree.size(); k++)            {                struct node * right = rightSubtree[k];                struct node * node = newNode(i);// making value i as root                node->left = left;              // connect left subtree                node->right = right;            // connect right subtree                list.push_back(node);           // add this tree to list            }        }    }    return list;} // Driver Program to test above functionsint main(){    // Construct all possible BSTs    vector<struct node *> totalTreesFrom1toN = constructTrees(1, 3);      /*  Printing preorder traversal of all constructed BSTs   */    cout << "Preorder traversals of all constructed BSTs are \n";    for (int i = 0; i < totalTreesFrom1toN.size(); i++)    {        preorder(totalTreesFrom1toN[i]);        cout << endl;    }    return 0;}
// A Java program to construct all unique BSTs for keys from 1 to nimport java.util.ArrayList;public class Main {     //  function for constructing trees    static ArrayList<Node> constructTrees(int start, int end)    {        ArrayList<Node> list=new ArrayList<>();        /*  if start > end   then subtree will be empty so returning NULL            in the list */        if (start > end)        {            list.add(null);            return list;        }           /*  iterating through all values from start to end  for constructing\            left and right subtree recursively  */        for (int i = start; i <= end; i++)        {            /*  constructing left subtree   */            ArrayList<Node> leftSubtree  = constructTrees(start, i - 1);               /*  constructing right subtree  */            ArrayList<Node> rightSubtree = constructTrees(i + 1, end);               /*  now looping through all left and right subtrees and connecting                them to ith root  below  */            for (int j = 0; j < leftSubtree.size(); j++)            {                Node left = leftSubtree.get(j);                for (int k = 0; k < rightSubtree.size(); k++)                {                    Node right = rightSubtree.get(k);                    Node node = new Node(i);        // making value i as root                    node.left = left;              // connect left subtree                    node.right = right;            // connect right subtree                    list.add(node);                // add this tree to list                }            }        }        return list;    }     // A utility function to do preorder traversal of BST    static void preorder(Node root)    {        if (root != null)        {            System.out.print(root.key+" ") ;            preorder(root.left);            preorder(root.right);        }    }     public static void main(String args[])    {        ArrayList<Node> totalTreesFrom1toN = constructTrees(1, 3);        /*  Printing preorder traversal of all constructed BSTs   */        System.out.println("Preorder traversals of all constructed BSTs are ");        for (int i = 0; i < totalTreesFrom1toN.size(); i++)        {            preorder(totalTreesFrom1toN.get(i));            System.out.println();        }    }} //  node structureclass Node{    int key;    Node left, right;    Node(int data)    {        this.key=data;        left=right=null;    }};//This code is contributed by Gaurav Tiwari
# Python3 program to construct all unique# BSTs for keys from 1 to n # Binary Tree Node""" A utility function to create anew BST node """class newNode:     # Construct to create a newNode    def __init__(self, item):        self.key=item        self.left = None        self.right = None # A utility function to do preorder# traversal of BSTdef preorder(root) :     if (root != None) :             print(root.key, end = " " )        preorder(root.left)        preorder(root.right)     # function for constructing treesdef constructTrees(start, end):     list = []     """ if start > end then subtree will be        empty so returning None in the list """    if (start > end) :             list.append(None)        return list         """ iterating through all values from        start to end for constructing        left and right subtree recursively """    for i in range(start, end + 1):             """ constructing left subtree """        leftSubtree = constructTrees(start, i - 1)         """ constructing right subtree """        rightSubtree = constructTrees(i + 1, end)         """ now looping through all left and            right subtrees and connecting            them to ith root below """        for j in range(len(leftSubtree)) :            left = leftSubtree[j]            for k in range(len(rightSubtree)):                right = rightSubtree[k]                node = newNode(i)   # making value i as root                node.left = left    # connect left subtree                node.right = right    # connect right subtree                list.append(node)    # add this tree to list    return list # Driver Codeif __name__ == '__main__':     # Construct all possible BSTs    totalTreesFrom1toN = constructTrees(1, 3)     """ Printing preorder traversal of        all constructed BSTs """    print("Preorder traversals of all",                "constructed BSTs are")    for i in range(len(totalTreesFrom1toN)):        preorder(totalTreesFrom1toN[i])        print() # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# program to construct all// unique BSTs for keys from 1 to nusing System.Collections;using System; class GFG{     // function for constructing trees    static ArrayList constructTrees(int start, int end)    {        ArrayList list = new ArrayList();                 /* if start > end then subtree will        be empty so returning NULL        in the list */        if (start > end)        {            list.Add(null);            return list;        }             /* iterating through all values from        start to end for constructing\        left and right subtree recursively */        for (int i = start; i <= end; i++)        {            /* constructing left subtree */            ArrayList leftSubtree = constructTrees(start, i - 1);                 /* constructing right subtree */            ArrayList rightSubtree = constructTrees(i + 1, end);                 /* now looping through all left and            right subtrees and connecting            them to ith root below */            for (int j = 0; j < leftSubtree.Count; j++)            {                Node left = (Node)leftSubtree[j];                for (int k = 0; k < rightSubtree.Count; k++)                {                    Node right = (Node)rightSubtree[k];                                         // making value i as root                    Node node = new Node(i);                                         // connect left subtree                    node.left = left;                                         // connect right subtree                    node.right = right;                                             // Add this tree to list                    list.Add(node);                        }            }        }        return list;    }     // A utility function to do    // preorder traversal of BST    static void preorder(Node root)    {        if (root != null)        {            Console.Write(root.key+" ") ;            preorder(root.left);            preorder(root.right);        }    }     // Driver code    public static void Main(String []args)    {        ArrayList totalTreesFrom1toN = constructTrees(1, 3);                 /* Printing preorder traversal        of all constructed BSTs */        Console.WriteLine("Preorder traversals of all" +                                "constructed BSTs are ");        for (int i = 0; i < totalTreesFrom1toN.Count; i++)        {            preorder((Node)totalTreesFrom1toN[i]);            Console.WriteLine();        }    }     // node structurepublic class Node{    public int key;    public Node left, right;    public Node(int data)    {        this.key=data;        left=right=null;    }};} // This code is contributed by Arnab Kundu
<script>  // node structureclass Node{    constructor(data)    {        this.key = data;        this.left = null;        this.right = null;    }}; // Javascript program to construct all// unique BSTs for keys from 1 to n// function for constructing treesfunction constructTrees(start, end){    var list = [];         /* if start > end then subtree will    be empty so returning NULL    in the list */    if (start > end)    {        list.push(null);        return list;    }     /* iterating through all values from    start to end for constructing\    left and right subtree recursively */    for (var i = start; i <= end; i++)    {        /* constructing left subtree */        var leftSubtree = constructTrees(start, i - 1);         /* constructing right subtree */        var rightSubtree = constructTrees(i + 1, end);         /* now looping through all left and        right subtrees and connecting        them to ith root below */        for (var j = 0; j < leftSubtree.length; j++)        {            var left = leftSubtree[j];            for (var k = 0; k < rightSubtree.length; k++)            {                var right = rightSubtree[k];                                 // making value i as root                var node = new Node(i);                                 // connect left subtree                node.left = left;                                 // connect right subtree                node.right = right;                                     // push this tree to list                list.push(node);                    }        }    }    return list;} // A utility function to do// preorder traversal of BSTfunction preorder(root){    if (root != null)    {        document.write(root.key+" ") ;        preorder(root.left);        preorder(root.right);    }}// Driver codevar totalTreesFrom1toN = constructTrees(1, 3); /* Printing preorder traversalof all constructed BSTs */document.write("Preorder traversals of all" +                        "constructed BSTs are<br>");for (var i = 0; i < totalTreesFrom1toN.length; i++){    preorder(totalTreesFrom1toN[i]);    document.write("<br>");}   </script>
Preorder traversals of all constructed BSTs are 
1 2 3 
1 3 2 
2 1 3 
3 1 2 
3 2 1 

This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
_Gaurav_Tiwari
SHUBHAMSINGH10
andrew1234
rutvik_56
surinderdawra388
simmytarika5
hardikkoriintern
Amazon
catalan
Binary Search Tree
Amazon
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
A program to check if a binary tree is BST or not
Find postorder traversal of BST from preorder traversal
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Optimal Binary Search Tree | DP-24
Sorted Array to Balanced BST
Inorder Successor in Binary Search Tree
Convert a normal BST to Balanced BST
set vs unordered_set in C++ STL
Find k-th smallest element in BST (Order Statistics in BST)
Check if a given array can represent Preorder Traversal of Binary Search Tree