120 likes | 259 Views
CS2223 Recitation 6 Finding the optimal Binary Search Tree for Keys with Given Probabilities. Song Wang April 20. Problem Definition. Binary Search Tree. 5. 2. 12. 4. Any key to the left of the root node is smaller than the node
E N D
CS2223 Recitation 6Finding the optimal Binary Search Tree for Keys with Given Probabilities Song Wang April 20
Problem Definition • Binary Search Tree 5 2 12 4 Any key to the left of the root node is smaller than the node Any key to the right of the root node is bigger than the node
Problem Definition • Binary Search Tree with Given Access Probabilities. 5(p=0.3) 2(p=0.1) 12(p=0.01) 4(p=0.59) Balanced BST is optimal only in case that all the access probabilities are equal: 1/n
Principle of Optimality • Given Pi for each key, Fn(p) is the expected cost (comparison) of finding a node in the BST, we have: For induction: P1,n
Principle of Optimality • Global optimal implies partial optimal: • Why is the 1? • It is the sum of all the probabilities in the BST.
A Running Example Greedy on probabilities E=2.37 E=2.17 E=2.02
Finding the Optimal BST C[i,j]=P[i,j]+min(C[i,r-1]+C[r+1,j]), i<=r<=j What we want is C[1,n]. We need to calculate P[i,j] first Filling order: 0. lower triangle: 0 1. Diagonal: Pi 2. P[i,j], on increasing i P[i,j]=
Finding the Optimal BST C[i,j]=P[i,j]+min(C[i,r-1]+C[r+1,j]), i<=r<=j We then calculate C[i,j] Filling order: 0. lower triangle: 0 1. Diagonal: P[i,i] 2. C[i,j] C[i,j]=
Finding the Optimal BST C[i,j]=P[i,j]+min(C[i,r-1]+C[r+1,j]), i<=r<=j P[i,j]= C[i,j]= 1 r=1, C[2,2] .22 r=2, C[1,1] .24 r=1 C[1,2]=P[1,2]+min 2 3 r=2, C[3,3] .23 r=3, C[2,2] .22 r=3 C[2,3]=P[2,3]+min 2 …… 4 r=4, C[5,5] .01 r=5, C[4,4] .3 r=4 C[4,5]=P[4,5]+min 5
Finding the Optimal BST C[i,j]=P[i,j]+min(C[i,r-1]+C[r+1,j]), i<=r<=j P[i,j]= C[i,j]= 2 r=1, C[2,3] .67 r=2, C[1,1]+C[3,3] .47 r=3, C[1,2] .68 r=2 C[1,3]=P[1,3]+min 3 1 r=2, C[3,4] .76 r=3, C[2,2]+C[4,4] .52 r=4, C[2,3] .67 r=3 C[2,4]=P[2,4]+min 3 4 2 ……
Finding the Optimal BST C[i,j]=P[i,j]+min(C[i,r-1]+C[r+1,j]), i<=r<=j P[i,j]= C[i,j]= r=1, C[2,5] 1.3 r=2, C[1,1]+C[3,5] 1.02 r=3, C[1,2]+C[4,5] 1 r=4, C[1,3]+C[5,5] 1.17 r=5, C[1,4] 1.99 r=3 C[1,5]=P[1,5]+min 3 4,5 1,2 Calculation order: by diagonals
Backtrack the Optimal BST • Recording every r during filling. r=1 r=3 C[i,j]= r=4 3 1 2 4 5