Optimal Binary Search Tree
We want to build a binary search tree which will contain keys K
1
to K
n
. They will be
searched for over time with probabilities β
1
to β
n
respectively. Also, keys not in the tree
whose values lie between Ki to K
i+1
are searched for with probability α
i
for i from
1 to n-1, keys < K
1
with probability α
0
and keys > K
n
with probability α
n
.
How can we build the tree so it has minimum weighted path length when α’s and β’s are
taken as the weights of the nodes? Such a tree is called an optimal binary search tree.
Discuss search through all trees - then how to construct the optimal tree and its
corresponding recursive solution - and its drawback in terms of execution time due to a
large number of repeated calls to solve the same problems.
Let
obst(i,j)
denote the optimal solution for the problem involving keys
K
i
to K
j
,
w
(i,
j
) its optimal weighted path length and
sw
(i,
j
) the sum of its weights. Then:
obst(i,j)
is obtained by
:
1. For
k
= i, . . . ,
j
find
obst(i,k-1)
and
obst(k+1,j).
2. Find a
k
that minimizes [
w
(i,
k
-1) +
w
(
k
+1,
j
)] over
k
= i, . . . ,
j
and let rij denote this
value of k.
3. The solution has root rij,
obst(i,
rij
-1)
as its left subtree, and
obst(
rij
+1,j)
as its
right subtree and
w
(i,
j
) =
sw
(i,
j
) +
w
(i, rij-1) +
w
(rij+1,
j
).
Solving our n key problem requires invoking
obst(1,n).
Obst(1,n)
is given by the tree with root
r1n,
obst(1,
r1n
-1)
as its left subtree, and
obst(
r1n
+1,n)
as its right subtree.
The weighted path length of
obst(1,n)
is
w
(1,
n
) where
w
(1,
n
) =
sw
(1,
n
) +
w
(1,
r1n
-1) +
w
(
r1n
+1,
n
).