Sie sind auf Seite 1von 21

AlgorithmforsearchoperationforBST

Bstnode search(int x,Bstnode t) { if(t==NULL) returnNULL; if(x<t>info) return t search(x,t h( t>left); l ft) elseif(x>t>info) returnsearch(x,t search(x t>right); else returnt; }
8Apr09 2

Search for an element may require less comparisons in left figure than the right figure figure. Hence, if a binary search tree is not balanced, the operations p like searching, g, insertion, , deletion takes considerable time as compared to a balanced binary search tree.

HeightofaTree
Definitionissameaslevel.Height g ofatreeisthelength g ofthe longestpathfromroottosomeleafnode. Heightofaemptytreeis1. Heightofasinglenodetreeis0. Recursivedefinition: height(t)=0ifnumberofnodes=1 =1ifTisempty max(height(LT) height(RT))otherwise =1+max(height(LT),

8Apr09

BalanceFactor
Balancefactorofanodeinabinarysearchtreeis thedifferencebetweenheightoftheleftsubtree andheightoftherightsubtree. BF=HL HR ,where, BF>Balance BalanceFactor HL>HeightofLeftSubtree HR>Height HeightofRightSubtree Hence,atreecanbeconsideredheightbalanced ifallitsnodeshaveabalancefactorwithinthe range(1,0,+1). So,foreverynodeinaheightbalancedtree BF{1,0,+1}

AVLTree So,tomakeatreebalancedafter insertionordeletion,weneedto followcertainrotationmethods devisedbythreescientistsnamed G M Ad l G.M.Adelson, Velskii, V l kii E.M.Landis. E M L di Hence,heightbalancedtreeisalso calledasAVLtree.

AVLRotations
AVLRotationsareof4types:: 1 LLRotations 1. 2.RRRotations 3.LRRotations 4 RLRotations 4.

LL Rotations
ptr temp p

ptr=root temp=ptr>left AfterRotation BeforeRotation ptr>left=temp>right temp>right=ptr

ptr

RR Rotations
temp

Before f Rotation i ptr=root

AfterRotation

temp=ptr>right ptr>right=temp>left temp>left=ptr

LR Rotation
p1

ptr

p2
p1=ptr 1 t >left l ft p2=p1>right p1>right=p2>left BeforeRotation p2>left=p1 AfterRotation ptr>left=p2 p p >right g p2>right=ptr ptr=p2

RL Rotation
ptr p1

p2 p1=ptr 1 >right i h p2=p1>left p1>left=p2>right BeforeRotation p2>right=p1 ptr>right=p2 p g p >left p2>left=ptr ptr=p2

AfterRotation

ExampletoBuildanAVLTree
Inputs are:::50,60,70,15,10,33,22,35,25,40

Das könnte Ihnen auch gefallen