130 likes | 411 Views
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
E N D
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
5 5 5 5 10 10 10 10 tmp 5 15 15 15 15 10 20 20 20 20 20 tmp 23 23 25 tmp 15 30 30 25 25 40 40 23 30 25 25 tmp 30 28 28 40 23 23 28 28 tmp 30 28 40 40 Transforming a BST into a backbone
gr gr Right rotation of child ch About parent par ch par par R p ch R Q p Q 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; }
the second phase Createperfecttree(n) { 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 25 15 20 5 10 25 30 20 20 23 30 5 15 15 23 40 28 10 23 23 40 25 28 5 15 25 28 28 30 30 40 40 M=3/2 Make 1 rotation M=7/2 Make 3 rotations First pass: make 9-7 rotations
tmp 5 10 20 15 30 40 25 Exercise-1 • Transfigure this tree into backbone • Then, create a perfect balanced binary search tree
5 10 15 20 23 25 28 30 40 60 Exercise-2 • Transfigure the backbone to create a perfect balanced binary search tree