//////////////////////////////////////////////////////////////////////////////////////////////////////////// //This Program is to implement optimal binary search tree //using dynamic programming /////////////////////////////////////////////////////////////////////////////////////////////////////////// import java.io.*; import java.util.*; class Optimal { public int p[]; // Probabilities with which we search for an element public int q[]; // Probabilities that an element is not found public int a[]; // Elements from which OBST is to be built public int w[][]; // Weight w[i][j] of a tree having root r[i][j] public int c[][]; // Cost c[i][j] of a tree having root r[i][j] public int r[][]; // Represents Root public int n; // Number of nodes int front,rear,queue[]; public Optimal(int SIZE) { p=new int[SIZE]; q= new int[SIZE]; a=new int[SIZE]; w=new int[SIZE][SIZE]; c=new int[SIZE][SIZE]; r=new int[SIZE][SIZE]; queue=new int[SIZE]; front=rear=-1; } /* This function returns a value in the range r[i][j-1] to r[i+1][j] so that the cost c[i][k-1] + c[k][j] is minimum */ public int Min_Value(int i, int j) { int m,k=0; int minimum = 32000; for (m=r[i][j-1] ; m<=r[i+1][j] ; m++) { if ((c[i][m-1]+c[m][j]) < minimum) { minimum = c[i][m-1] + c[m][j]; k = m; } } return k; } /* This function builds the table from all the given probabilities It basically computes C,r,W values */ public void OBST() { int i, j, k, l, m; for (i=0 ; ijavac Optimal.java D:\DAA_MU>java OBSTDemo Optimal Binary Search Tree Enter the number of nodes 4 Enter the data as .... a[1]1 a[2]2 a[3]3 a[4]4 p[1] 3 p[2] 3 p[3] 1 p[4] 1 q[0] 2 q[1] 3 q[2] 1 q[3] 1 q[4] 1 The Optimal Binary Search Tree For The Given Nodes Is .... The Root of this OBST is :: 2 The Cost Of this OBST is :: 32 NODE LEFT CHILD RIGHT CHILD ------------------------------------------------------- 2 1 3 1 - - 3 - 4 4 - - D:\DAA_MU>