×

Optimal binary search tree using dynamic programming

Implementation

// We are creating a presentation where we will present a recursive method of the optimal binary search tree problem. 
#include <bits/stdc++.h>
using namespace std;


//creating a utility function that will help us extract the sum of the array elements containing the frequency i and j.  
int sum(int frequency[], int i, int j);


// building a new function that will ultimately help us get out the cost of the optimal binary search tree. 
int optCost(int frequency[], int i, int j)
{
	if (j < i) 
		return 0;
	if (j == i) 
		return frequency[i];
	
	//In this step, we have to get the sum of the i and i+1…… frequency j. 
	int freqsum = sum(frequency, i, j);
	
	// regularizing the minimal value or data.
	int min = INT_MAX;
	
	// We have to start initializing all the data or records one at a time and consider all the elements there as root. Then after this is done, we have to find the cost of the binary search tree, compare that cost with the minimal record, and make the changes consecutively if required.
	for (int r = i; r <= j; ++r)
	{
		int cost = optCost(frequency, i, r - 1) +
				optCost(frequency, r + 1, j);
		if (cost < min)
			min = cost;
	}
	
	// at this step, we have to return the minimal value.
	return min + freqsum;
}


// Now, we are simply creating the main function that will help us calculate and adjust the minimal cost of the binary search tree. It will help us optimize the tree's optimal cost and locate it easily.
int Opt_SearchTree(int kys[],
					int frequency[], int n)
{
	// In this step, it is presumed that the array keys should be arranged in increasing order. And if the keys present there are not set accordingly, we have to add some code and make the required changes. After this, we can also change the frequency of the same. 
	return optCost(frequency, 0, n - 1);
}


// We are creating a utility function that will help us to get the sum of the frequency of the elements present in that specific array. 
int sum(int frequency[], int i, int j)
{
	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 "
		<< Opt_SearchTree(kys, frequency, n);
	return 0;
}

Output:

Optimal binary search tree using dynamic programming

Example 2)

// We are creating a presentation where we will present a recursive method of the optimal binary search tree problem. 
#include <stdio.h>
#include <limits.h>
//creating a utility function that will help us extract the sum of the array elements containing the frequency i and j.  
int sum(int frequency[], int i, int j);
// building a new function that will ultimately help us get out the cost of the optimal binary search tree. 
int optCost(int frequency[], int i, int j)
{
if (j < i)	
	return 0;
if (j == i)	
	return frequency[i];
//In this step, we have to get the sum of the i and i+1…… frequency j. 
int freqsum = sum(frequency, i, j);
// regularizing the minimal value or data.
int min = INT_MAX;
	// We have to start initializing all the data or records one at a time and consider all the elements there as root. Then after this is done, we have to find the cost of the binary search tree, compare that cost with the minimal record, and make the changes consecutively if required.
for (int r = i; r <= j; ++r)
{
	int cost = optCost(frequency, i, r-1) +
				optCost(frequency, r+1, j);
	if (cost < min)
		min = cost;
}
	// at this step, we have to return the minimal value.
return min + freqsum;
}
// Now, we are simply creating the main function that will help us calculate and adjust the minimal cost of a binary search tree. It will help us optimize the tree's optimal cost and locate it easily.
int Opt_SearchTree(int kys[], int frequency[], int n)
{
	// In this step, it is presumed that the array keys should be arranged in increasing order. And if the keys present there are not set accordingly, we have to add some code and make the required changes. After this, we can also change the frequency of the same. 
	return optCost(frequency, 0, n-1);
}
// We are creating a utility function that will help us to get the sum of the frequency of the elements present in that specific array. 
int sum(int frequency[], int i, int j)
{
	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]);
	printf("Cost of Optimal BST is %d ",
			Opt_SearchTree(kys, frequency, n));
	return 0;
}

Output:

Optimal binary search tree using dynamic programming

Example 3)

// We are creating a presentation where we will present a recursive method of the optimal binary search tree problem. 
public class TFG
{
	//creating a utility function that will help us extract the sum of the array elements containing the frequency i and j.  
	static int optCost(int frequency[], int i, int j)
	{
	if (j < i)	 
		return 0;
	if (j == i)
		return frequency[i];
	
// building a new function that will ultimately help us get out the cost of the optimal binary search tree. 
//In this step, we have to get the sum of the i and i+1…… frequency j. 
	int freqsum = sum(frequency, i, j);
// regularizing the minimal value or data.
	int min = Integer.MAX_VALUE;
// We have to start initializing all the data or records one at a time and consider all the elements there as root. Then after this is done, we have to find the cost of the binary search tree, compare that cost with the minimal record, and make the changes consecutively if required.
	for (int r = i; r <= j; ++r)
	{
		int cost = optCost(frequency, i, r-1) +
						optCost(frequency, r+1, j);
		if (cost < min)
			min = cost;
	}
	// at this step, we have to return the minimal value.
	return min + freqsum;
	}
// Now, we are simply creating the main function that will help us calculate and adjust the minimal cost of a binary search tree. It will help us optimize the tree's optimal cost and locate it easily.
	static int Opt_SearchTree(int kys[], int frequency[], int n)
	{
			// In this step, it is presumed that the array keys should be arranged in increasing order. And if the keys present there are not set accordingly, we have to add some code and make the required changes. After this, we can also change the frequency of the same. 
		return optCost(frequency, 0, n-1);
	}
	// We are creating a utility function that will help us to get the sum of the frequency of the elements present in that specific array. 
	static int sum(int frequency[], int i, int j)
	{
		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 " +
						Opt_SearchTree(kys, frequency, n));
	}
}

Output:

Optimal binary search tree using dynamic programming

Example 4)

# We are creating a presentation where we will present a recursive method of the optimal binary search tree problem. 
def optCost(frequency, i, j):
		if j < i:	
		return 0
	if j == i:	 
		return frequency[i]
//In this step, we have to get the sum of the i and i+1…… frequency j. 
	freqsum = Sum(frequency, i, j)
	
	# regularizing the minimal value or data.
	Min = 999999999999
	
	# We have to start initializing all the data or records one at a time and consider all the elements present in there as root. Then after this is done, we have to find the cost of the binary search tree, compare that cost with the minimal record, and make the changes consecutively if required.
	for r in range(i, j + 1):
		cost = (optCost(frequency, i, r - 1) +
				optCost(frequency, r + 1, j))
		if cost < Min:
			Min = cost
	
	# at this step, we have to return the minimal value.


	return Min + freqsum


# Now, we are simply creating the main function that will help us calculate and adjust the minimal cost of a binary search tree. It will help us optimize the tree's optimal cost and locate it easily.
def Opt_SearchTree(kys, frequency, n):
	
	# In this step, it is presumed that the array keys should be arranged in increasing order. And if the keys present there are not set accordingly, we have to add some code and make the required changes. After this, we can also change the frequency of the same. 
	return optCost(frequency, 0, n - 1)


# We are creating a utility function to help us get the sum of the frequency of the elements present in that specific array. 
def Sum(frequency, i, j):
	s = 0
	for k in range(i, j + 1):
		s += frequency[k]
	return s


# writing the main code.
if __name__ == '__main__':
	kys = [10, 12, 20]
	frequency = [34, 8, 50]
	n = len(kys)
	print("Cost of Optimal BST is",
		Opt_SearchTree(kys, frequency, n))

Output:

Optimal binary search tree using dynamic programming

Example 5)

// We are creating a presentation where we will present a recursive method of the optimal binary search tree problem. 
using System;
class TFG
{
//creating a utility function that will help us extract the sum of the array elements containing the frequency i and j.  
	static int optCost(int []frequency, int i, int j)
	{
		
	if (j < i)	
		return 0;
	if (j == i)	
		return frequency[i];
// building a new function that will ultimately help us get out the cost of the optimal binary search tree. 
//In this step, we have to get the sum of the i and i+1…… frequency j. 
	int freqsum = sum(frequency, i, j);
// regularizing the minimal value or data.	
	int min = int.MaxValue;
	// We have to start initializing all the data or records one at a time and consider all the elements there as root. Then after this is done, we have to find the cost of the binary search tree, compare that cost with the minimal record, and make the changes consecutively if required.
	for (int r = i; r <= j; ++r)
	{
		int cost = optCost(frequency, i, r-1) +
						optCost(frequency, r+1, j);
		if (cost < min)
			min = cost;
	}
	// at this step, we have to return the minimal value.
	return min + fsum;
	}
// Now, we are simply creating the main function that will help us calculate and adjust the minimal cost of a binary search tree. It will help us optimize the tree's optimal cost and locate it easily.
	static int Opt_SearchTree(int []kys, int []frequency, int n)
	{
	// In this step, it is presumed that the array keys should be arranged in increasing order. And if the keys present there are not set accordingly, we have to add some code and make the required changes. After this, we can also change the frequency of the same. 
		return optCost(frequency, 0, n-1);
	}
// We are creating a utility function that will help us to get the sum of the frequency of the elements present in that specific array. 
	static int sum(int []frequency, int i, int j)
	{
		int s = 0;
		for (int k = i; k <=j; k++)
		s += frequency[k];
		return s;
	}
// writing the main code.	
	public static void Main()
	{
		int []kys = {10, 12, 20};
		int []frequency = {34, 8, 50};
		int n = kys.Length;
		Console.Write("Cost of Optimal BST is " +
						Opt_SearchTree(kys, frequency, n));
	}
}

Output:

Optimal binary search tree using dynamic programming

Example 6)

<script>
// We are creating a Javascript presentation where we will present a recursive method of the optimal binary search tree problem. 
function optCost(frequency, i, j)
{
	if (j < i) 
		return 0;
	if (j == i) 
		return frequency[i];
//creating a utility function that will help us extract the sum of the array elements containing the frequency i and j.  
// building a new function that will ultimately help us get out the cost of the optimal binary search tree. 
//In this step, we have to get the sum of the i and i+1…… frequency j. 
	var freqsum = sum(frequency, i, j);
// regularizing the minimal value or data.	
	var min = Number. MAX_SAFE_INTEGER;
	// We have to start initializing all the data or records one at a time and consider all the elements there as root. Then after this is done, we have to find the cost of the binary search tree, compare that cost with the minimal record, and make the changes consecutively if required.
	for (var r = i; r <= j; ++r)
	{
		var cost = optCost(frequency, i, r - 1) +
				optCost(frequency, r + 1, j);
		if (cost < min)
			min = cost;
	}
	// at this step, we have to return the minimal value.
	return min + fsum;
}
// Now, we are simply creating the main function that will help us calculate and adjust the minimal cost of a binary search tree. It will help us optimize the tree's optimal cost and locate it easily.
function Opt_SearchTree(kys, frequency, n)
{
	// In this step, it is presumed that the array keys should be arranged in increasing order. And if the keys present there are not set accordingly, we have to add some code and make the required changes. After this, we can also change the frequency of the same. 
	return optCost(frequency, 0, n - 1);
}
// We are creating a utility function that will help us to get the sum of the frequency of the elements present in that specific array. 
function sum(frequency, i, j)
{
	var s = 0;
	for (var k = i; k <= j; k++)
	s += frequency[k];
	return s;
}




// writing the main code.	
var kys = [10, 12, 20];
var frequency = [34, 8, 50];
var n = kys.length;
document.write("Cost of Optimal BST is " +
	Opt_SearchTree(kys, frequency, n));
	</script>

Output:

Optimal binary search tree using dynamic programming

Related Topics

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.

Asynchronous advantage actor-critic (A3C) Algorithm

The Asynchronous advantage actor-critic (A3C) Algorithm is one of the latest algorithms developed by the Artificial Intelligence division, Deep Mind at Google. It is used for the Deep Reinforcement Learning...

3 minutes read.

Common Operations on various Data Structures

Data structures are ways to organise data in computer memory for quick and effective use. The storage of data uses a variety of data-structures. It is also possible to define...

7 minutes read.

Red Black Tree

Red Black Tree A red-black tree is referred as self-balancing binary search tree. The tree was invented by Rudolf Bayer in 1972. In red-black, each node stores an extra bit that...

8 minutes read.

Buffer overflow attack with examples

You have undoubtedly faced the term buffer overflow in your programming journey. Many times it occurs when we try to run a piece of code with user input, but it...

4 minutes read.

Function to Insert a Node in a Binary Search Tree

Implementation // writing C++ code that will help us in implementing the insertion operation in a binary search tree. #include <bits/stdc++.h> using namespace std; // creating a new binary search tree node struct __nod { int...

8 minutes read.

Linear Search

Searching: In the data structure, searching is the process in which an element is searched in a list that satisfies one or more than one condition. Types of searching There are two...

4 minutes read.

Given a Binary Tree, Print the Pre-order Traversal in Recursive

Implementation #include <stdio.h> #include <stdlib.h>   /* Creating a binary tree node that consists of some data along with the pointer to the left and right child.  */ struct __nod {     int record;     struct...

4 minutes read.

What Should We Learn First? Trees or Graphs in Data Structures

A data structure is a database used to store and manage data and optimize and manage computing resources. A data structure is a form used intelligently and quickly to store,...

6 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Stack vs Heap Memory Allocation Data Structure

Difference Between Stack and Heap Memory Allocation Stack Memory Stack memory allocation is a way to use the system memory as a temporary storage of the data which is act like last-in-first-out...

3 minutes read.

Perfect Binary Tree

Complete binary trees are an important and general topic in the concept – of tree data structures. Before discussing a complete binary tree, we need to know the concept of...

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

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.

Tree vs Graph: Data Structure

Difference Between Tree and Graph What is Tree? A tree is a non-linear data structure and finite collection of elements called node. A tree, in which the data items are arranged in...

3 minutes read.

Treap data structure

In this article, we will discuss the treap data structure. The word treap is a combination of 'tree' and 'heap'. So, treap data structure is a combination of a heap...

8 minutes read.

Bucket Sort

Bucket Sort: In the sorting algorithm, we create buckets and put elements into them. We can apply some sorting algorithm (insertion sort) to sort the elements in each bucket. Finally,...

4 minutes read.

Find the fractional (n/kth) node in the linked list

Find the fractional (n/kth) node in the linked list In this problem, we have given a singly linked list and a number k. Here we need to find the (n/k)th element...

2 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.