Dynamic Programming 3
Dynamic Programming 3
Algorithm Notes
Dynamic Programming-3
By
Dr. K. V. Arya
ABV-IIITM, Gwalior, India
Binary Search Tree
The Deletion Operation
To delete x from the BST:
Procedure search can be modified to return
the node v that has value x (instead of a
boolean value) . Once this has been found,
there are four cases.
1. v is a leaf.
this just remove v from the tree. 2
The deletion operation
2. v has exactly one child w, and v is not the root.
v w
X
3
The deletion operation
3. v has exactly one child w, and v is the root.
v
X
w
4
The deletion operation
4. v has 2 children.
This is the interesting case . First, find the smallest element s in
the right sub tree of v (using procedure min). Delete s (note that
this uses case 1 or 2 above). Replace the value in node v with s.
v
10 12
5 15 5 15
s
2 7 12 2 7 13
5
13
Binary search tree
• Note : could have used largest in left sub tree for s.
8
The average case is O(log n)
Average Case Analysis
What is the average case running time for n insertions into
an empty BST ? Suppose we insert x1, ….xn, where x1 < x2 <
…xn (not necessarily inserted in that order). Then
ascending order,
Average Case Analysis
• x1,…xj-1 : these go to the left of the root; needs j -1
comparisons to root, T(j-1) comparisons to each other.
13
Depth of a Node
• Definition: The Depth of a node v is
• 0 if v is the root.
• d + 1 if v’s parent has depth d.
0 15
1 5
2 10
2
3
7 12
14
Cost of a Node
Let depth (xi ) be the depth of the node v with l(v)= xi.
Number of comparisons for search (xi,S) is
depth(xi) + 1.
depth(i).
∑ ph(depth(xh) + 1) + ∑ qh depth(h).
h=1 h=0
real fictitious
Given the probabilities , we want to find the BST that
minimizes the value.
nodes
xi+1,……..,xj
T i,j
i j
17
Constructing Ti,j
• To find the best tree Ti,j :
xk
Ti,k-1 Tk,j
18
Computing Ci, j
ci , j (ci, k 1 wi , k 1) (ck , j wk , j ) pk
19
Dynamic Programming
Algorithm
To compute the cost of the minimum cost BST , store c i, j in a
table c[i,j] , and store wi, j in a table w[i , j].
for i:= 0 to n do
W[i,i]:= qi
C[i,i]:= 0
for l:=1 to n do
for i:=0 to n-l do
j:= I + l
w[i , j]:= w[I,j-1] = p j + q j
c[i ,j] := min i<k≤j (c[i,k-1] + c[k,j] + w[I,j])
Correctness : similar to earlier examples. 20
Analysis: O(n3)