×

Given a Generate all Structurally Unique Binary Search Trees

Implementation

// Creating a C++ program that will help us build all the binary search trees for the keys from 1 to n. 
#include <bits/stdc++.h>
using namespace std;


// creating a structure that will contain some nodes.
struct __nod
{
	int ky;
	struct __nod *Lft, *Rt;
};


// creating a new utility function to help create a new binary search tree node. 
struct __nod *new__nod(int itm)
{
	struct __nod *temp = nw__nod;
	temp->ky = itm;
	temp->Lft = temp->Rt = NILL;
	return temp;
}


// Creating a utility function that will generally help us in performing the pre-order traversal for the binary search tree. 
void Pre_Ord(struct __nod *root)
{
	if (root != NILL)
	{
		cout << root->ky << " ";
		Pre_Ord(root->Lft);
		Pre_Ord(root->Rt);
	}
}


// creating a new function that will help create a new tree.
vector<struct __nod *> constructTrees(int start, int end)
{
	vector<struct __nod *> list;


	/* if we have a case where the start > end, then the subtree will be empty, and we will return the NILL values in the list. */
	if (start > end)
	{
		list.push_back(NILL);
		return list;
	}


	/* we have to repeatedly recapitulate among all the values from the beginning to the end to build the left and right subtree. */
	for (int i = start; i <= end; i++)
	{
		/* we will now create the left subtree */
		vector<struct __nod *> LftSubtree = constructTrees(start, i - 1);


		/* we will now create the right subtree */
		vector<struct __nod *> RtSubtree = constructTrees(i + 1, end);


		/* Now, we have to move in the coil format through the various left and right subtrees and connect to the root below. */
		for (int j = 0; j < LftSubtree.size(); j++)
		{
			struct __nod* Lft = LftSubtree[j];
			for (int k = 0; k < RtSubtree.size(); k++)
			{
				struct __nod * Rt = RtSubtree[k];
				struct __nod * __nod = new__nod(i);// making value i as root
				__nod->Lft = Lft;			 // connect Lft subtree
				__nod->Rt = Rt;		 // connect Rt subtree
				list.push_back(__nod);		 // add this tree to list
			}
		}
	}
	return list;
}


// writing the main program for the above functions.
int main()
{
	// building the binary search tree
	vector<struct __nod *> totalTreesFrom1toN = constructTrees(1, 3);




	/* Printing Pre_Ord traversal of all constructed BSTs */
	cout << "Pre_Ord traversals of all constructed BSTs are \n";
	for (int i = 0; i < totalTreesFrom1toN.size(); i++)
	{
		Pre_Ord(totalTreesFrom1toN[i]);
		cout << endl;
	}
	return 0;
}

Output:

Given a Generate All Structurally Unique Binary Search Trees

Example 2)

// Creating a C# program will help us build all the binary search trees for the keys from 1 to n. 
using System.Collections;
using System;


class TFT
{
// creating a structure that will contain some nodes.
	static ArrayList constructTrees(int start, int end)
	{
		ArrayList list = new ArrayList();
/* if we have a case where the start > end, then the subtree will be empty, and we will return the NILL values in the list. */
		if (start > end)
		{
			list.Add(NILL);
			return list;
		}
	/* we have to repeatedly recapitulate among all the values from the beginning to the end to build the left and right subtree. */
		for (int i = start; i <= end; i++)
		{
			/* we will now create the left subtree*/
			ArrayList LftSubtree = constructTrees(start, i - 1);
	
			/* we will now create the right subtree*/
			ArrayList RtSubtree = constructTrees(i + 1, end);
	/* Now, we have to move in the coil format through the various left and right subtrees and connect to the root below.*/
			for (int j = 0; j < LftSubtree.Count; j++)
			{
				__nod Lft = (__nod)LftSubtree[j];
				for (int k = 0; k < RtSubtree.Count; k++)
				{
					__nod Rt = (__nod)RtSubtree[k];
					
					// change i into the root.
					__nod __nod = nw__nod(i);
					
					// linking with the left subtree
					__nod.Lft = Lft;
					
					// linking with the right subtree
					__nod.Rt = Rt;	
					
					// merging the tree with the list
					list.Add(__nod);		
				}
			}
		}
		return list;
	}
// Creating a utility function that will generally help us in performing the pre-order traversal for the binary search tree. 
	static void Pre_Ord(__nod root)
	{
		if (root != NILL)
		{
			Console.Write(root.ky+" ") ;
			Pre_Ord(root.Lft);
			Pre_Ord(root.Rt);
		}
	}
// writing the main program for the above functions.
	public static void Main(String []args)
	{
		ArrayList totalTreesFrom1toN = constructTrees(1, 3);
		
		/* printing the pre-order traversal of all the already built binary search trees. */
		Console.WriteLine("Pre_Ord traversals of all" +
								"constructed BSTs are ");
		for (int i = 0; i < totalTreesFrom1toN.Count; i++)
		{
			Pre_Ord((__nod)totalTreesFrom1toN[i]);
			Console.WriteLine();
		}
	}
// creating a structure that will contain some nodes.	
public class __nod
{
	public int ky;
	public __nod Lft, Rt;
	public __nod(int record)
	{
		this.ky=record;
		Lft=Rt=NILL;
	}
};
}

Output:

Given a Generate All Structurally Unique Binary Search Trees

Example 3)

// Creating a Java program that will help us build all the binary search trees for the keys from 1 to n. 
import java.util.ArrayList;
public class Main {
// creating a structure that will contain some nodes.
// creating a new utility function to help create a new binary search tree node. 
	static ArrayList<__nod> constructTrees(int start, int end)
	{
		ArrayList<__nod> list=new ArrayList<>();
/* if we have a case where the start > end, then the subtree will be empty, and we will return the NILL values in the list. */
		if (start > end)
		{
			list.add(NILL);
			return list;
		}
/* we have to repeatedly recapitulate among all the values from the beginning to the end to build the left and right subtree. */
		for (int i = start; i <= end; i++)
		{
			/* we will now create the left subtree  */
			ArrayList<__nod> LftSubtree = constructTrees(start, i - 1);


			/* we will now create the right subtree  */
			ArrayList<__nod> RtSubtree = constructTrees(i + 1, end);


			/* Now, we have to move in the coil format through the various left and right subtrees and connect to the root below.*/
			for (int j = 0; j < LftSubtree.size(); j++)
			{
				__nod Lft = LftSubtree.get(j);
				for (int k = 0; k < RtSubtree.size(); k++)
				{
					__nod Rt = RtSubtree.get(k);
					__nod __nod = nw__nod(i);	 // change i into the root.
					__nod.Lft = Lft;	// linking with the left subtree
					__nod.Rt = Rt;		// linking with the right subtree
					list.add(__nod);	// merging the tree with the list
	
				}
			}
		}
		return list;
	}
// Creating a utility function that will generally help us in performing the pre-order traversal for the binary search tree. 
	static void Pre_Ord(__nod root)
	{
		if (root != NILL)
		{
			System.out.print(root.ky+" ") ;
			Pre_Ord(root.Lft);
			Pre_Ord(root.Rt);
		}
	}


	public static void main(String args[])
	{
		ArrayList<__nod> totalTreesFrom1toN = constructTrees(1, 3);
			/* printing the pre-order traversal of all the already built binary search trees. */
		System.out.println("Pre_Ord traversals of all constructed BSTs are ");
		for (int i = 0; i < totalTreesFrom1toN.size(); i++)
		{
			Pre_Ord(totalTreesFrom1toN.get(i));
			System.out.println();
		}
	}
}


// creating a structure that will contain some nodes.
class __nod
{
	int ky;
	__nod Lft, Rt;
	__nod(int record)
	{
		this.ky=record;
		Lft=Rt=NILL;
	}
};

Output:

Given a Generate All Structurally Unique Binary Search Trees

Example 4)

# Creating a Python program to help us build all the binary search trees for the keys from 1 to n. 


# Creating a new utility function to help create a new binary search tree node. 
class new__nod:


	# Creating a new function that will help create a new tree.
	def __init__(self, itm):
		self.ky=itm
		self.Lft = None
		self.Rt = None


# Creating a utility function to help us perform the pre-order traversal for the binary search tree. 
def Pre_Ord(root) :


	if (root != None) :
	
		print(root.ky, end = " " )
		Pre_Ord(root.Lft)
		Pre_Ord(root.Rt)
	list = []


	""" if we have a case where the start > end, then the subtree will be empty, and we will return the NILL values in the list. """
	if (start > end) :
	
		list.append(None)
		return list
	
	" < UNK> < UNK> We have to recapitulate among all the values from the beginning to the end to build the left and right subtree repeatedly. """
	for i in range(start, end + 1):
	
		""" we will now create the left subtree """
		LftSubtree = constructTrees(start, i - 1)


		""" we will now create the right subtree """
		RtSubtree = constructTrees(i + 1, end)


		""" Now, we have to move in the coil format through the various left and right subtrees and connect to the root below. """
		for j in range(len(LftSubtree)) :
			Lft = LftSubtree[j]
			for k in range(len(RtSubtree)):
				Rt = RtSubtree[k]
				__nod = new__nod(i) # change i into the root.
				__nod.Lft = Lft # linking with the left subtree
				__nod.Rt = Rt # linking with the right subtree
				list.append(__nod) # merging the tree with the list
	return list


# writing the main code.
if __name__ == '__main__':


	# we have to build all the possible binary search trees
	totalTreesFrom1toN = constructTrees(1, 3)


	""" printing the pre-order traversal of all the already built binary search trees."""
	print("Pre_Ord traversals of all",
				"constructed BSTs are")
	for i in range(len(totalTreesFrom1toN)):
		Pre_Ord(totalTreesFrom1toN[i])
		print()

Output:

Given a Generate All Structurally Unique Binary Search Trees

Example 5)

<script>
// creating a structure that will contain some nodes.
class __nod
{
	constructor(record)
	{
		this.ky = record;
		this.Lft = NILL;
		this.Rt = NILL;
	}
};


// // Creating a Javascript program that will help us in building all the binary search trees for the keys from 1 to n. 
function constructTrees(start, end)
{
	var list = [];
/* if we have a case where the start > end, the subtree will be empty, and we will return the NILL values in the list. */	
	if (start > end)
	{
		list.push(NILL);
		return list;
	}
/* we have to repeatedly recapitulate among all the values from the beginning to the end to build the left and right subtree. */
	for (var i = start; i <= end; i++)
	{
		/* we will now create the left subtree */
		var LftSubtree = constructTrees(start, i - 1);


		/* we will now create the right subtree */
		var RtSubtree = constructTrees(i + 1, end);
/* we have to repeatedly recapitulate among all the values from the beginning to the end to build the left and right subtree. */
		for (var j = 0; j < LftSubtree.length; j++)
		{
			var Lft = LftSubtree[j];
			for (var k = 0; k < RtSubtree.length; k++)
			{
				var Rt = RtSubtree[k];
				// change i into the root.
				var __nod = nw__nod(i);
				// linking with the left subtree
				__nod.Lft = Lft;
				// linking with the right subtree
				__nod.Rt = Rt;	
				// pushing the tree with the list
				list.push(__nod);		
			}
		}
	}
	return list;
}
// Creating a utility function that will generally help us in performing the pre-order traversal for the binary search tree. 
function Pre_Ord(root)
{
	if (root != NILL)
	{
		document.write(root.ky+" ") ;
		Pre_Ord(root.Lft);
		Pre_Ord(root.Rt);
	}
}
// writing the main program for the above functions.
var totalTreesFrom1toN = constructTrees(1, 3);


/* printing the pre-order traversal of all the already built binary search trees. */
document.write("Pre_Ord traversals of all" +
						"constructed BSTs are<br>");
for (var i = 0; i < totalTreesFrom1toN.length; i++)
{
	Pre_Ord(totalTreesFrom1toN[i]);
	document.write("<br>");
}
</script>

Output:

Given a Generate All Structurally Unique Binary Search Trees

Related Topics

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

What is Skewed Binary Tree

To understand the skewed binary tree, we must first understand the concept of a binary tree. A binary is generally the one in which every single node has two further...

3 minutes read.

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

6 minutes read.

Convert binary tree to a doubly linked list

Implementation //creating a C++ program for the transition of a binary tree into a linked list. #include <iostream> using namespace std; /* Firstly, let’s create a binary tree that will help us in setting...

4 minutes read.

Breadth First Search

Breadth First Search Breadth first search is a graph traversing algorithm. In this, we start traversing from the source node or any selected node and traverse the graph layer by layer....

6 minutes read.

Deque in Data Structure

Deque A deque referred as “Double-Ended Queue”, is a linear collection of data items same like queue data structure. deque has two ends, front end and rear end, deque is the...

27 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Deletion in B+ Tree

Make a search for the leaf node that containing the key value by taking the value in a key value. If the required key value is found, then it will remove...

6 minutes read.

Radix Sort

Radix Sort: The radix sort is a non-comparative integer sorting algorithm that sorts the elements by grouping the individual digits of the same location. It shares the same significant position...

4 minutes read.

Red Black Tree vs AVL Tree: Data Structure

Difference Between Red Black Tree vs AVL Tree Red Black Tree: A red-black tree is referred as self-balancing binary search tree. In red-black, each node stores an extra bit that determines...

4 minutes read.

Applications of trees in data structures

Data structures Storage used to organize and store data is known as the data structure. It is a method of managing computerized data to translate or retrieve it more efficiently. A...

7 minutes read.

Delete N nodes after M nodes of a linked list

Delete N nodes after M nodes of a linked list In this problem, we have given a linked list and two integers M and N. We need to traverse the linked...

3 minutes read.

B+ Tree Program in Q language

A B+ tree is just an improvised version of a self-balancing and well-maintained tree in which all the key values that hold valuable information is present at the bottom, which...

9 minutes read.

What are Forest Trees in Data Structure

Data structure A data model manages and optimizes computer resources, and a database stores and manages data. It's one of many uses for data structures to hold data. Data structures come...

5 minutes read.

Assembly Line Scheduling

If we take an example of a car factory, there are two assembly lines. In an assembly line, we can assemble and repair the parts of a car. Now, suppose...

5 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

Boruvkas algorithm

This algorithm is used for finding minimum spanning tree from a weighted graph. Like prim’s and kruskal’s algorithm it is also a greedy algorithm. Note:What is the minimum spanning tree?We know...

4 minutes read.

Bubble Sort in Data Structures

Bubble Sort in C++ The bubble sort algorithm analyses two adjacent elements and swaps them until they are no longer in the desired order. Each iteration moves each member of the array...

4 minutes read.