0% found this document useful (0 votes)
13 views7 pages

Avl

Avl tree

Uploaded by

Shruthi S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views7 pages

Avl

Avl tree

Uploaded by

Shruthi S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

f

Tri!@ Strur.tur@,. 221


llata !,tr11ct 11 rr~ ~nd Al :11ri1h111 ~ ~
220 ~ ell f s libtree.le rt is None
. or suhtree .right i• NQTle : f
Rt'movlng an l■lt'rlor ~od• .-tth y 11-., Childrrt1 if s uhtree. left 1s not None : !
I
return subtree.left
If the node to L.... d I t_.., h h'I I n 111••11 fin d the nndc w ith smaller valu
• '"' C C "" ai. tW(l 1.' 1 l I'\' • ' e in else :
the ""'" ,ubtttt "' fond th< """' •i•h ; ;,:," ,·,h>' ;o ''" kft subt ree. Rcrlaee the
return subtree.right
node in rt~ of dclc-ted m'lllc. else
Node I 5 ha."~" children. bc>th (lfwhich arc the rol1t s oflhcir_own subtrees . To delete successor = self.bstMinimum( subtree.right )
node 15, find 1M smallC!o nodc in the tight subn·ee. That ts 23. Afte r finding the subtree.key = successor.key
1
clement. rcr•~ it to 1M node containing the clement being removed. Now the nod subtree.value = successor.value
subtree.right = self.bstRemove( subtree.right. successor.key )
I 5 is deleted. e
return subtree
6_7 AVLTREE
• The AVL tree, was invented by G. M. Adelson-Velsk.ii and Y . \.1. Landis in
1962, improves on the binary search tree by always guaranteeing the tree is

height balanced, which allows for more efficient operations.
• A binary tree is balanced if the heights of the left and right §Ubtren of every
node differ by at most 1.
fs: (35 • Balance Factor= Height of Left Sub Tree - Height of Right Subtree
• Maintaining a balanced tree, ensure its height never aceeds l.-'"' log n. This
height is sufficient for providing O (log n) time operations even in the wont
Figure 6.13 Deleting a Node 15
case.
Function IO delete elements from the binary Search tree
Example 1: Balanced A VL tree
def bstRemovc( self, subtree, target ):
if subtree is !',;one :
return subtree
elif w get < subtree .key :
subtree.left = klf.bstRemove( subtree.left, target )
return subtree
eliftarget > liubtree.lc.-y :
subtree.right = lid f. b!.1Remove( i.ubtrt:e .right, target )
return subtree
else :
if subtree.left is None 11nd i.ubtrtt .ngli1 i1, Nuut :
return None
i A!G11r ttht11 ~
222 fl,1111 Stnlflllrf'~ f!l1t
~ ..--- Tree Struct1Jre, 223
Eumple 2: lmbalanl't'd trrt'. Nc,C an 1' ,·a. trrc case 3: rnserting a node a'! a right child of left subtree
[TT-21.._ ln1lmlancc-J Case 4: Inserting a node a, a left child of right subtree.
t,) -
• 1
f the insertion occur, on the outside of the subtree (left- left or right-right) then
0-0- 0
it is handled by the single mtation
• If the insertion occur, on the in,ide of the subtree <left-right or right-left) then it
J. handled by the double rotation
·s
c ase I : Slngle Rotation with Left


binary search tree.
.
The insertion

.
The !'iC&TCh and tniven;al OJX'rat,ons are the same with an A VL tree as With a
. operations have to be modi
. and dcIetion
·fi d · d ·
. maintain
. te m or er to .
the balance rrorertY of the tree as new keys are mserted and existing ones
ranc,,,ed.

-
.., .• 1■9ft"INa
Routine to perform Single Rotation with left
In A\ 'l. trcc, the n"- key iii added at the child node. When the new key is inserted
into an A\'l. trcc. the balance property of the tree must be maintained. If the insertion def avlSingleRotateRight( self, k2 ):
of thc ncv.· key C&WiQ any of the subtrees to become unbalanced, they must be kl = k.2.left
rebalanced. k.2.left = kl.right
k I .right = k2
Rotatiottt
k.2.height = 1 + max.(self.Height(U.left). !IClf.HcigblcC.nght))
Muluple subtrees can become unbalanced after inserting a new key. To handle this kl.height= 1 + max.(selt:Heigh[\kl.left), !1Clf.Hetpqkl.nll,ht))
return kl
the ~rs1 suhtrcc encountered this out of balance has to be rebalanced. The root node
ofttu, subtree ,s known as the pivot node.
Case 2: Single Rotadoa witla Ri&lllt
An A VL subtree i, rd>alanced by performing a rotation around the pivot node. This
involvei. rCM1TV,gmg the luu-' of the pivot node, its children, and possibly one of its
grandc::hildrc:n. The acrw.f modific111ion~ depend on which descendant's subtree of the
pivot node the new ley wiu. mi>en.ed inl.(J and the b11lance factors.
There Ille fUUJ p<,i.~1lilc c&~b :
Cbe t : ln~nmg II nod<' 1:11, 11 ldt tl,ild of left 1>ubtree
Ca., 2, ln~n '"' • m,d, " • "'"" d.,Jd of, ;Kin •uht,ee _
~
-
.h.;..m_s_ _ _ _ __
.2~2:!4_ _ _ _ _ _ _ __!D~a~ta~S~tru~cn~,r~es::_;a~n'.!!d..'.:A~lg~o~rit;;:.;
Routine to perfonn Single Rotation with Right
---
~--- -- Tree Structures
225

'
Routine to perform double rotation with left
def avlSingleRotateLeft( self, k I ):
def avlDoubleRota~eRight( self, kI ):
k2 =kl.right
k I .Right= avlSmgleRotateleft( k I .left)
k I.right = k2.left
return avlSingleRotateRigh t(k I)
k2.left = kl
k2.height = 1 + max(self.Height(k2.left), self.Height(k.2.right))
kl.height= 1 + max(self.Height(kl.left), self.Height(kl.right)) After a rotation is performed, the balance factor of the impacted nodes has to be
changed to reflect the new node heights.
return k2
Implementation for insertion
Case 3: Left Right Double Rotation
def insert(self,root,key):
if not root:
return node(key)
elif key < root.data:
root.left= self.insert(root.IeftJcey)
else:
root.right= self.insert(root.right,key)
root.height= 1 + max(self.Height(root.left), self.Height(root.right))
BF = self.calculateBalanc e(root)
Routine to perform double rotation with left
If BF > 1 and key < root.left.data:
def avlDoubleRotateLeft ( self, k3 ): Return self. avlSingleRotateRight (root)
k3.left= avlSingleRot.ateRigbt(k3 .left) If BF < -1 and key > root.right.data:
return avlSingleRotateleft(k 3) Return self. avlSingleRotateLeft (root)
If BF > 1 and key < root.left.data:
Case 4: Right Left Double Rotation Root.left=self. avlDoubleRotateleft (root.left)
If BF < -1 and key < root.right.data:
Root.right=self. avlDoubleRotateright (root.right)
Return root
Example:
Insert I, 2, 3, 4, 5, 6, 7
Insert I
CD 0-()o:()
l'lalil Strurturrs 1111<1 Al11nr1thrn s
--
226
~ Tr.,, Strur.tur.,, 227
lnsen 2
fnHCrt 6
~ - 1-- 1
\)0-0-0
ln11en 3
K,
u
~ 0-0-(l
U Do n.,tation
~1-0
(D0+.o @~
lnscn 4
Insert 7
0-2--2 +-ID~ mad
In:scn 5
G--2~-z -- d o ~
:::::>
~F(J
228
Insert 16

(lata Stnlft11res rind A.!E_orithlllS


-........ -
Jn scrt 14

Tree Structures
229
1- 3~-2 4-- to be rotate
~
lnwrt 15
Insert 13
K.
tL
__,,,
Tree Structures
230
d Algorithms
Data Structures a!,_ -.... 231
fo Jnsert 11
Insert 12
3-1 ~2 .- To be rotated
.IJ Require single rotation.
u
23J
lalft't 11

('l,ata Strurt11rf'S a~orithll1S


-- tn~crt 9

Tree Structures 233


JJ ..._
"'-•brt....i
ij.
lata1 I
6,7.2 Deledon
~hen a node is removed from an A\'L tree. it must ensure that the balance property
15 maintained. In the insertion operation. at most ooc suberee can become unbalanced.
After the appropriate rotation is ~~ on the sublree. the balance factors of the
~'~e's anceston do not change. Thu.i. it ...:stores the height-balance property both
OCidly at the subtree and globally for the entire tree.

You might also like