×

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

Hash Table vs STL Map

Hash table and STL map are extremely valuable information structures in software engineering. Here we will consider the examination between their properties to be well as execution.  To start with, we will...

7 minutes read.

Huffman tree in Data Structures

The Huffman trees in the field of data structures are pretty impressive in their work. They are generally treated as the binary tree, which is linked with the least external...

6 minutes read.

2-3 Trees and Basic Operations on them

2-3 Trees, like any other AVL trees or B-trees, are just a type of Height Balanced Tree. 2-3 Trees are the B-trees of order 3. Like every other B-tree, the...

4 minutes read.

Vertical Order Traversal of Binary Tree

Implementation #include <iostream> #include <vector> #include <map> using namespace std; // representing the primary model of a binary tree node. struct _nod { int ky; _nod *Lft, *Rt; }; // establishing a new function representing the new binary tree node. struct _nod*...

5 minutes read.

Function to Create a Copy of Binary Search Tree

Implementation // creating a new hashmap in the language C++ that will help us clone a binary tree with arbitrary pointers.  #include<iostream> #include<unordered_map> using namespace std; /* A given binary tree has a record, a...

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.

Binary Tree Implementation Using Arrays

Implementation Converting a binary tree into a list of arrays is one interesting problem. Let us see that in depth. In this section, we will see the implementation of the binary Trees...

4 minutes read.

Deletion in Binary Search Tree

Implementation #include <iostream> using namespace std; struct _nod {   int ky;   struct _nod *Lft, *Rt; }; // Creating a node in the binary tree. struct _nod *nw_nod(int Itm) {   struct _nod *temp = (struct _nod *)malloc(sizeof(struct...

4 minutes read.

Stack Using Linked List

In the linked list implementation of the stack, we use a linked list as the primitive data structure to create the stack. It is called the dynamic implementation of the...

6 minutes read.

Sort the linked list of 0s, 1s and 2s

Sort the linked list of 0s, 1s and 2s In this, we are given a linked list of 0s, 1s, and 2s, and we need to sort it. Examples: Input: 1  ->  1 ...

2 minutes read.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Insertion Sort in Data Structures

Insertion Sort in C++ Insertion sort is a sorting algorithm that, in each iteration, installs an unsorted element in its proper position Insertion sort operates in a similar way to how we...

3 minutes read.

Difference Between Linear and Non Linear Data Structures

Data Structure A data structure is a data object together with the relationships between the instances and the individual elements that compose an instance. These relationships are defined by the operations...

5 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Dijkstra’s vs Bellman-Ford Algorithm

The Dijkstra Algorithm One of the SSSP (Single Source Shortest Path) algorithms is Dijkstra's. As a result, it finds the shortest path between a source node and all other nodes in...

7 minutes read.

Tree terminology in Data structures

Data structures The storage used to organize and store data is known as a data structure, and it is a method where data can be arranged on a computer to be...

6 minutes read.

Linked List Representation of Binary Tree

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. The word binary itself represents its meaning; we know that...

4 minutes read.

Rotate a Singly Linked List

Rotate a Singly Linked List This article will explain how we can rotate the singly linked list. Here we have given a singly linked list, and we need to rotate this...

4 minutes read.

Recursion - Factorial and Fibonacci

In this article, we will learn how to find the factorial of a number and the Fibonacci series up to n using the recursion method. What is recursion? Defining anything in terms...

7 minutes read.

Stack Using Array

Stack – A Stack is a linear abstract data type used to store elements. It is also called last in first out or first in last out data structure because...

6 minutes read.