CS331 Advanced Data Structures – Spring 2016 Optimal Binary Search Tree Problem The Problem : Given n key values k1 , k2 , . . . , kn and probabilities p1 , p2 , . . . , pn and q0 , q1 , . . . , qn where pi = probability of key ki being searched for qi = probability of value v between ki and ki+1 being searched for (i.e, a failed search) determine an optimal binary tree that will minimize the expected number of nodes visited. The Recurrence Relation : Let e(i, j) = w(i, j) = expected value for optimal BST containing keys ki through kj , j X pl + l=i j X qj . l=i−1 Then ( e(i, j) = qi−1 , j = i − 1, min (e(i, r − 1) + e(r + 1, j) + w(i, j), j ≥ i i≤r<j ( w(i, j) = qi−1 , j = i − 1, w(i, j − 1) + pj + qj , j ≥ i The Code : int optimalBST(double [] p, double [] q) { int n = p.length()-1; int [][] e = new int[n+2][n+1]; int [][] w = new int[n+2][n+1]; for(int i=1; i<=n+1; i++) e[i][i-1] = w[i][i-1] = q[i-1]; for(int b=0; b<n; b++) // b = distance from main diagonal for(int i=1; i<=n-b; i++) { int j = i+b; w[i][j] = w[i][j-1] + p[j] + q[j]; e[i][j] = e[i][i-1] + e[i+1][j] + w[i][j]; for(int r=i+1; r<=j; r++) { tmp = e[i][r-1] + e[r+1][j] + w[i][j]; if (tmp < e[i][j]) e[i][j] = tmp; } } return e[1][n]; } The Time Complexity : T (n) = O(n3 ).