tmp

advertisement
DSW algorithm
DSW algorithm
• To avoid sorting, it required deconstructing
and then reconstructing the tree, which is
inefficient except for relatively small trees
• DSW algorithm require little additional
storage for intermediate variables and use
no sorting procedure
• Devised by Colin Day and improved by
Quentin F. Stout and Bette L. Warren
• First phase: The DSW algorithm
transfigures an arbitrary BST into a link
listlike tree called a backbone (or a vine).
• Second phase: This elongated tree is
transformed in a series of passes into a
perfected tree by repeatedly rotating every
second node of the backbone about its
parent
First phase
Createbackbone(root,n)
{ tmp=root;
while (tmp!=null)
if (tmp has a left child)
rotate this child about tmp;
//hence the left child became parent of tmp
set tmp to the child which just became parent
else set tmp to the right child
Transforming a BST into a backbone
5
5
5
5
5
10
10
tmp
20
15
30
25
23
tmp
30
40
28
25
23
40
28
20
20
20
20
15
15
15
15
10
10
10
23
23
25
tmp
23 30
28 40
25
25
30
28 40
tmp
28
30
40
tmp
The building block for the tranformations is the
rotation. (rotate right, left)
Rotateright(gr,par, ch)
{
if par is not the root of the tree //i.e., if gr isn’t null
grandparent gr of child ch becomes ch’s parent by replacing par;
right subtree of ch becomes left subtree of ch’s parent par;
node ch acquires par as its right child;
}
gr
gr
Right rotation of child ch
About parent par
par
R
ch
p
Q
ch
par
p
Q
R
Createperfecttree(n)
the second phase
{
m=2└ lg(n+1)┘ -1;
Make n-m rotations starting from the top of backbone;//first pass
while (m>1)
{ m=m/2;
Make m rotations starting from the top of backbone;
}
}
In the second phase, the backbone is transformed into a tree, but this time, the
tree is perfectly balanced by having leaves only on two adjacent levels. In each
pass down the backbone, every second node is rotated about its parent. On
such pass decreases the size of the backbone by one-half. But the first
pass…
5
10
10
20
20
5
15
15
25
10
23
5
20
25
23
28
40
30
40
First pass:
make 9-7 rotations
10
40
5
30
M=7/2
Make 3 rotations
M=3/2
Make 1 rotation
30
20
30
15 23
28
28
25
25
23
15
28
40
Exercise-1
5
• Transfigure this tree into
backbone
• Then, create a perfect balanced
binary search tree
tmp
10
20
15
30
25
40
Exercise-2
5
10
• Transfigure the backbone to
create a perfect balanced binary
search tree
15
20
23
25
28
30
40
60
Download