Optimal Binary Search Tree
Optimal Binary Search Tree
Tree
Binary search tree, the nodes in the left subtree have lesser value than
the root node and
the nodes in the right subtree have greater value than the root node.
The optimal binary search tree (Optimal BST) is also known as a weight-
balanced search tree.
It is a binary search tree that provides the shortest possible search time
or expected search time.
An optimal binary search tree is helpful in dictionary search.
Search Cost and Tree Structure
The cost of searching in a binary search tree depends on the structure of
the tree and the number of comparisons required to reach the desired
identifier.
The overall cost of searching a node should be less.
Let's understand through an example.
= 6C3/(3+1)
=20/4
=5
So we can see that 5 trees will be formed as shown in the figure given
below.
In this case, the total number of comparisons is less as compared to others
because the height of the tree is less. So we can say that it’s a balanced binary
Let's assume that frequencies associated with the keys 15,
25, 35 are 3, 2, 5.
=1 x3 +2 x 2+ 3 x 5=22 =1 x3 +2 x 5+ 3 x =1 x5 +2 x 3+ 3 x
2=19 2=17
=1 x2 +2 x 3+ 2x =1 x5 +2 x 2+ 3 x
5=18 3=18
Dynamic Approach
Consider the below table, which contains the keys and
frequencies.
Cost would be: 1*6 + 2*2 + 3*4 = 22 Cost would be: 1*6 + 2*4 + 3*2 = 20
Therefore, the minimum cost is 20 which is the 3rd root. So, c[0,3] is equal to 20.
It can also be done using the formula
C[0,3]=
w(0,3)=
w(0,3)=f(1)+f(2)+f(3)
w(0,3)=4+2+6=12
C[0,3]= Node 10 as key Node 20 as key Node 30 as key
since 1 is the key than c[0,1-1] + c[1,j] + w(0,3)
c[0,0] + c[1,3] + w(0,3)
since 2 is the key than c[0,2-1] + c[2,j] + w(0,3)
c[0,1] + c[2,3] + w(0,3)
since 3 is the key than c[0,3-1] + c[3,j] + w(0,3)
c[0,2] + c[3,3] + w(0,3)
c[0,3]=min{c[0,0] + c[1,3] + w(0,3),
c[0,1] + c[2,3] + w(0,3), C[i,r−1]+C[r,j]+w(i,j)
c[0,2] + c[3,3] + w(0,3) }
c[0,3]=min{0 + 10 + 12,
4+ 6 + 12,
8+ 0 +12 }
When i=1 and j=4 then we will consider the keys 20, 30, 40
c[1,4] = min{
c[1,2-1] + c[2,4],
c[1,3-1] + c[3,4] ,
c[1,4-1] + c[4,4]
} + 11
c[1,4] = min{
c[1,1] + c[2,4],
c[1,2] + c[3,4] ,
c[1,3] + c[4,4]
} + 11
= min{
0+12, 2+3, 10+0}+ 11
= min{12, 5, 10} + 11
The minimum value is 5; therefore, c[1,4] = 5+11 = 16
When i=0 and j=4 then we will consider the keys 10,20, 30, 40
W(0,4)=4+2+6+3=15
c[0,4] = min{
c[0,0] + c[1,4],
c[0,1] + c[2,4] ,
c[0,2] + c[3,4] ,
c[0,3] + c[4,4]
} + 15
c[0,4] = min{
0 + 16,
4 + 12,
C[i,r−1]+C[r,j]+w(i,j)
8+3,
20 +0
} + 15
r(0,4)
3
r(0,2) r(3,4)
since3 is the remainin after key
key
1 4
r(1,2)
r(0,0)
since1 is the
since1 is the
key
key 2
r(0,4)
30
r(0,2) r(3,4)
since3 is the remainin after key
key
10 40
r(1,2)
r(0,0)
since1 is the
since1 is the
key
key 20