×

Optimal binary search tree in DSA

Implementation

// A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.  
#include <bits/stdc++.h>
using namespace std;


// we have to create a basic utility function to help us get the sum of both the frequencies present. 
int sm(int frequency[], int g, int k);


// creating a function that is recursive and also a function that will help us in estimating the cost of the optimal binary search tree. 
int optimal__Cost(int frequency[], int g, int k)
{
	if (k < g) 
// this subarray is empty, which implies it doesn't contain any elements in them.
		return 0;
	if (k == g) // this subarray contains one type of element.
		return frequency[g];
	
	// in this subarray we have to get the sum of the following frequencies:- frequency[g], frequency [g+1], frequency[k]. 
	int fsm = sm(frequency, g, k);
	// we have to initialize the latest minimal value and see where it goes:-
	int minimum= INT__MAX;
	
	// start considering all the elements present but one by one
	// then we have to find the cost of the root and recursive
	// present in the BST and then compare this cost with the
	// minimum val and then update if required.
	for (int r = g; r <= k; ++r)
	{
		int cost = optimal__Cost(frequency, i, r - 1) +
				optimal__Cost(frequency, r + 1, j);
		if (cost < min)
			minimum= cost;
	}
	
	// Return minimum value
	return minimum+ fsm;
}


// now create the main function that will calculate the minimum cost of a particular binary tree, and it will possibly only use the optimal__Cost() function to find the optimal cost of the binary search tree.
int optimal search tree(int kys[],
int frequency[], int n)
{
	// given the array keys here are presumed to be aligned, which will be in increasing order. If the keys are not aligned, then we have to technically add a code to solve and arrange the keys and refigure the frequency of the same accordingly.
	return optimal__Cost(frequency, 0, n - 1);
}


//creating a utility function that will help us get the sum of the elements of the array and the frequency of the gth and kth elements. 
int sm(int frequency[], int g, int k)
{
	int s = 0;
	for (int k = g; k <= h; k++)
	s += frequency[k];
	return s;
}


// writing the main code.
int main()
{
	int kys[] = {10, 12, 20};
	int frequency[] = {34, 8, 50};
	int n = sizeof(kys) / sizeof(kys[0]);
	cout << "Cost of Optimal BST is "
		<< optimalSearchTree(kys, frequency, n);
	return 0;
}

Output:

Optimal binary search tree in DSA

Example 2)

// A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.  
#include <bits/stdc++.h>
using namespace std;
// in this subarray we have to get the sum of the following frequencies:- frequency[g], frequency [g+1], frequency[k]. 
int sm(int frequency[], int g, int k);
// creating a function that is recursive and also a function that will help us in estimating the cost of the optimal binary search tree. 
int optimalSearchTree(int kys[], int frequency[], int n)
{
	int cost[n][n];


	/* cost[i][j] = Optimal cost of binary search tree
	that can be formed from kys[i] to kys[j].
	cost[0][n-1] will store the resultant cost */


	// if we are calculating the cost for a single key, then the frequency can be calculated by: -
	for (int g = 0; g < n; g++)
		cost[g][g] = frequency[g];
	// we will now see whether we can see the chains of the length or not, which is 2, 3… 
	for (int L = 2; L <= n; L++)
	{
		// g is considered as the row number in cost[][]
		for (int g = 0; i <= n-L+1; i++)
		{
			// we have to get the column number h from the row number g
			// chain length L
			int k = g+L-1;
			cost[g][h] = INT__MAX;
			int off_set_sm = sm(frequency, i, j);


			// we have to try and convert all the keys present as root. 
			for (int r = i; r <= j; r++)
			{
			// c is generally the cost of the tree when keys are the root of this subtree. 
			int c = ((r > i)? cost[i][r-1]:0) +
					((r < j)? cost[r+1][j]:0) +
					off_set_sm;
			if (c < cost[i][j])
				cost[i][j] = c;
			}
		}
	}
	return cost[0][n-1];
}
// in this subarray we have to get the sum of the following frequencies:- frequency[g], frequency [g+1], frequency[k]. 
int sm(int frequency[], int g, int k)
{
	int s = 0;
	for (int k = i; k <= j; k++)
	s += frequency[k];
	return s;
}


// writing the main code.
int main()
{
	int kys[] = {10, 12, 20};
	int frequency[] = {34, 8, 50};
	int n = sizeof(kys)/sizeof(kys[0]);
	cout << "Cost of Optimal BST is " << optimalSearchTree(kys, frequency, n);
	return 0;
}

Output:

Optimal binary search tree in DSA

Example 3)

//creating a utility function that will help us get the sum of the elements of the array and the frequency of the gth and kth elements. 
int sm(int frequency[], int g, int k);
// creating a function that is recursive and also a function that will help us in estimating the cost of the optimal binary search tree. 
int optimal search tree(int kys[], int frequency[], int n)
#include <stdio.h>
#include <limits.h>
//creating a 2D matrix will help us store all the essential problems.
	int cost[n][n];
/* cost[i][j] = Optimal cost of binary search tree
	that can be formed from kys[i] to kys[j].
	cost[0][n-1] will store the resultant cost */


// if we are calculating the cost for a single key, then the frequency can be calculated by: -
	for (int g = 0; i < n; i++)
		cost[i][i] = frequency[i];
	// we will now see whether we can see the chains of the length or not, which is 2, 3… 
	// L is chain length.
	for (int L=2; L<=n; L++)
	{
		// g is row number in cost[][]
		for (int g=0; i<=n-L+1; i++)
		{
		// we have to get the column number h from the row number g
			// chain length L
			int k = i+L-1;
			int off_set_sm = sm(frequency, i, j);
			cost[i][j] = INT__MAX;
// we have to try and convert all the keys present as root. 
			for (int r=i; r<=j; r++)
			{
		// c is generally the cost of the tree when keys are the root of this subtree. 
			int c = ((r > i)? cost[i][r-1]:0) +
					((r < j)? cost[r+1][j]:0) +
					off_set_sm;
			if (c < cost[i][j])
				cost[i][j] = c;
			}
		}
	}
	return cost[0][n-1];
}
// in this subarray we have to get the sum of the following frequencies:- frequency[g], frequency [g+1], frequency[k]. 
int sm(int frequency[], int g, int k)
{
	int s = 0;
	for (int k = i; k <=j; k++)
	s += frequency[k];
	return s;
}


// Driver program to test the above functions
int main()
{
	int kys[] = {10, 12, 20};
	int frequency[] = {34, 8, 50};
	int n = sizeof(kys)/sizeof(kys[0]);
	printf("Cost of Optimal BST is %d ",
				optimalSearchTree(kys, frequency, n));
	return 0;
}

Output:

Optimal binary search tree in DSA

Example 4)

// A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.  
#include <stdio.h>
#include <limits.h>
// creating a function that is recursive and also a function that will help us in estimating the cost of the optimal binary search tree. 
int sm(int frequency[], int g, int k);
int optimal__Cost(int frequency[], int g, int k)
{
If (j < i)	 //, this subarray is empty, which implies it doesn't contain any elements in them.
	return 0;
if (j == i) // this subarray contains one type of element.
	return frequency[i];
// in this subarray we have to get the sum of the following frequencies:- frequency[g], frequency [g+1], frequency[k]. 


int fsm = sm(frequency, i, j);


// Initialize minimum value
int minimum= INT__MAX;
// we have to initialize the latest minimal value and see where it goes:-
// start considering all the elements present but one by one
	// then we have to find the cost of the root and recursive
	// present in the BST and then compare this cost with the
	// minimum val and then update if required.
for (int r = i; r <= j; ++r)
{
	int cost = optimal__Cost(frequency, i, r-1) +
				optimal__Cost(frequency, r+1, j);
	if (cost < min)
		minimum= cost;
}


// Return minimum value
return minimum+ fsm;
}
// now create the main function that will calculate the minimum cost of a particular binary tree, and it will possibly only use the optimal__Cost() function to find the optimal cost of the binary search tree.
int optimalSearchTree(int kys[], int frequency[], int n)
{
	// given the array keys here are presumed to be aligned, which will be in increasing order. If the keys are not aligned, then we have to technically add a code to solve and arrange the keys and refigure the frequency of the same accordingly.
	return optimal__Cost(frequency, 0, n-1);
}
//creating a utility function that will help us get the sum of the elements of the array and the frequency of the gth and kth elements. 
int sm(int frequency[], int g, int k)
{
	int s = 0;
	for (int k = i; k <=j; k++)
	s += frequency[k];
	return s;
}


// Driver program to test the above functions
int main()
{
	int kys[] = {10, 12, 20};
	int frequency[] = {34, 8, 50};
	int n = sizeof(kys)/sizeof(kys[0]);
	printf("Cost of Optimal BST is %d ",
			optimalSearchTree(kys, frequency, n));
	return 0;
}

Output:

Optimal binary search tree in DSA

Example 5)

// A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.  
public class TFM
{
// creating a function that is recursive and also a function that will help us in estimating the cost of the optimal binary search tree. 
	static int optimal__Cost(int frequency[], int g, int k)
	{
	If (j < i)	 //, this subarray is empty, which implies it doesn't contain any elements in them.
		return 0;
	if (j == i)	// this subarray contains one type of element.
		return frequency[i];
// in this subarray we have to get the sum of the following frequencies:- frequency[g], frequency [g+1], frequency[k]. 	
	int fsm = sm(frequency, i, j);
	// we have to initialize the latest minimal value and see where it goes:-
	int minimum= Integer.MAX_VALUE;
// start considering all the elements present but one by one
	// then we have to find the cost of the root and recursive
	// present in the BST and then compare this cost with the
	// minimum val and then update if required.	
	for (int r = i; r <= j; ++r)
	{
		int cost = optimal__Cost(frequency, i, r-1) +
						optimal__Cost(frequency, r+1, j);
		if (cost < min)
			minimum= cost;
	}
	
	// Return minimum value
	return minimum+ fsm;
	}
// now create the main function that will calculate the minimum cost of a particular binary tree, and it will possibly only use the optimal__Cost() function to find the optimal cost of the binary search tree.	
	static int optimalSearchTree(int kys[], int frequency[], int n)
	{
	// given the array keys here are presumed to be aligned, which will be in increasing order. If the keys are not aligned, then we have to technically add a code to solve and arrange the keys and refigure the frequency of the same accordingly.
		return optimal__Cost(frequency, 0, n-1);
	}
	//creating a utility function that will help us get the sum of the elements of the array and the frequency of the gth and kth elements. 
	static int sm(int frequency[], int g, int k)
	{
		int s = 0;
		for (int k = i; k <=j; k++)
		s += frequency[k];
		return s;
	}
	
	// writing the main code.
	public static void main(String[] args) {
		int kys[] = {10, 12, 20};
		int frequency[] = {34, 8, 50};
		int n = kys.length;
		System.out.println("Cost of Optimal BST is " +
						optimalSearchTree(kys, frequency, n));
	}
}

Output:

Optimal binary search tree in DSA

Related Topics

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

Quick Sort vs Merge Sort

In this article, we will take an overview of Quick Sort and Merge Sort and then discuss the differences between them. What is Quick Sort? Quick Sort – The idea behind the...

7 minutes read.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

7 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

Applications of Different Linked Lists in Data Structure

What is a Linked list? A linked list is a data structure that consists of a sequence of elements, where each containing a reference or ("link") to the next element in...

5 minutes read.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

What is a Threaded Binary Tree?

When we consider those binary trees that are interlinked with each other, we do come across the fact that the fields present in there do consist of NULL values that...

3 minutes read.

Data Structures Algorithms

What is an Algorithm? An algorithm is a sequence of steps used to complete a job or get a desired result. It is similar to programming building elements that let cell...

4 minutes read.

Finding Rank in a Binary Search Tree

Implementation // writing a C++ program to find out the rank and element in the program.  #include <bits/stdc++.h> using namespace std; struct __nod { int record; __nod *Lft, *Rt; int LftSize; }; __nod* new__nod(int record) { __nod *temp = new __nod; temp->record...

6 minutes read.

Trim a binary search tree

Implementation //writing a C++ program will help us eliminate the keys that are out of the league.  #include<bits/stdc++.h> using namespace std; //we are now creating a binary search tree node consisting of key left...

8 minutes read.

Extended Binary Tree

A form of binary tree known as an extended binary tree replaces all of the original tree's null subtrees with special nodes known as external nodes, while the remaining nodes...

4 minutes read.

Cycle sort

Cycle sort is an examination arranging calculation which powers exhibit to be figured into the quantity of cycles where every one of them can be pivoted to create an arranged...

5 minutes read.

All About Minimum Cost Spanning Trees in Data Structure

Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system that stores, manages, and optimizes...

7 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

Finding the Minimum and Maximum Value of a Binary Tree

Implementation // Writing a C++ program that will help us find out the maximum and the minimum in a binary tree.  #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new class tree node. class...

5 minutes read.

Invert binary tree

Invert binary tree is a mirror image of a tree. It is pretty much the same compared to the only difference: its left and right children are swapped with the...

4 minutes read.

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree,...

4 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

3 minutes read.

Introduction to Arrays

What exactly is an array? A group of related data pieces stored in contiguous memory regions is referred to as an array. It is the most basic data structure in which...

5 minutes read.