Data Structures and Algorithms Unit-4 Notes

You might also like

Download as pdf
Download as pdf
You are on page 1of 54
UNIT-4 Sree Inbioduckion Binony [ees re Thee Tronercol wo banely tru (est) Definition ope a BST Snsertien ils 0 BST Deletion pen a BST AVL Thees Scanned with CamScanner dreoeer = D bra bluclion means thet the dala. ane orgamizeel in 0. hivrarrhical manner Definition - A bee in o finile sok ef ome oF mete modes bucly that 7 © Shore is a specially dsiqnaded. node called te ‘oot’ a nw ened infe nZzO dij dk Eh Te whue tach etre 200 wy obec. Too in one called the éublizes of poet - Dhow ane many tome that an opin used wher ing Te Wises. NOU stands jo the item of, informakion plus Hie branches bo oth modes - Consens He brie below + Level (A) 4. ® B ‘ bob 8 ® oO % a | 4300 ‘389 } > | sapssajolg Iesy “INDIGGIS VNVUINNS * Scanned with CamScanner “This Vie has 15 modes, tach tom of data. bung a ingle in Jor comriniomee - The noel i A / > he number of Aubbraue of a mode, is called de + The eof ABs CBA ood of Fie Gre G 2 >The nodes that hare dogeue ger ane called bof wr “fonminal: modes”. © $kyl, FoGsMs 1,74 is the sek of lat noodles => Com 5 the oth node ort Atfored to ab “Wilner? XX ke the Sparen” ee aula Dow Ho Zand Ts the panunt elden ofthe ore pre ane ido be 1 © Kible 2, ee a Til slp Sith ¢ i te mati Pe Oe the nodes in the ; a We abere im the figue: hos degre 5 The ‘amenstoss” a node ore all the ned along "ai patly from he sort that node. Scanned with CamScanner sa on A, Domd H leh? of a node is defined by . red bot ones ak shen tk chillin ove ot le ©L44? LL, ha hight dip? ohn Us dade the maximum beth op ty moda ihe The dnt eh the Fw the fae 4 List nepsendatain of the bie +45 Elk orucenttation zi Hap e[-platol ae chidd - Ke c bible SUNMRANA SIDDIQUI " Asst. Professor * CSE, DCET Scanned with CamScanner @) : @—_©— 60 6 m-©—-© O_O @) To obtain the degres “tuo Five reprustrtetion of a- ae » hotnte the right-sibling poirilars im au left child - ight aibling Tree olockwice by 45 degen Scanned with CamScanner > SUMRANA SiDDIQUI » Borie MakeBT(bt4» ne vty hate A Bi Fra” is av finite wok of modes tod is tthe. ea consitle s a soot and two dispeink- bin ate the left sublie omd the gpa dublin fuotls 6 & ADT Bina Tree ‘ri node either wv Objiele + + fea ered ond cong % e : ight nat pee Fumekions ° fl fox, oll, be bit, bb2 € BinanyTnue » te Birla CaO t= crecilis om a a) az If (bb=s omply Ol i ne a] ‘oetwm Tue ae netuam False ‘tum 5 bt2) #= seliem binary item € dement Pree whose. ft f bho. a whose Oe eins Ye dale tem: : : nie Hk (Ysbmplg (LED seb oer BinTce Lasiaca = we ua qe Scanned with CamScanner Fe elernent> Dal.(bt) == If (Beko (bt)) Telit Unor else adie the In the re0t node of bb BainTrce Rebidel (bt) #= if (2s&mply Ct) reli ener elec qpekwonr the mgt sublize of bb - ond. Binary Tree Dictinekion between a Binasy Thee omd a Thee * Firat, thee is m0 bux honing geno nodes, but there & om ee : ao Tree the wider othe childern ate io The Oloove ‘hap pinay oe One different since Hine finet binag bite has om omp right sublize while the second hat an ome! bublbice . Viewed. Ou tre, Hoey aos Sent » draw, slightly dlifhesunaty > bho U Tue - this bimany bee all the mods howe only either one child 92 no child 5 cam be sl ckowedl etthr to the lift 64.46 the vighit Scanned with CamScanner Lett shaved Bina Te Right shoe Binany Thee Compl: Binary Tre ~4f i 0 Binary Tee im which i” 7 Ol the lovele or compli filled. except: possibly the lowest one, Whiely is fjlled fom the left Buna “4 iu “any True in whol alll Full: Tree - Ut ts 0 Brrany D. nods have O ev two childun- ® © © © 7 oe sguwkaxasiopiaul.— @). (E) 6 6 ® “i, Asst, Professor * °° OSE, DCET © © Scanned with CamScanner Rappesdiant oltDinent ilnees © The ‘anime cruumber oh modes on love” i? oh ay Vice ue ae @ Th mnaninnum ruwmber eh Oh Trades im a. binary beer af dupth “k? i akt, hed. © Fer any sron emply binary bine oTs th Mo the anwmbey modss Oond. Ny Ub the mmmber of- nodes of dope 2 » sthen Mp =Ngt 1. —> Binary Tree Repruerntadions Pavan Repruuntation - Using a one dimendional from 45 tee the node, Mumbered ae Atlee. Steteel . Position 0 tet with “n? nooles ae then for ang mode with india i et © parent (1) is ak life) if F#1°Y ie d.0 a ak root amd has mo parent ® igegila (> in ot dip dian. 2 >nothen ‘ho mo let child . @ machi (1) in ak Aird If isd on. Y dirdon, | thon t has no aighd child | Scanned with CamScanner i (yee be used for all binawy ; erg Co S27 " an will be a lat of wnuilieal space. ideal , Wee the ruertation is 1 For complete a ert Toc WL tkaved fie however as mo bpace lus thary half te Ore is wig {o} us (4 BI 4 I (J 3) | ta SUMRANA SiDDiQu Asst Professor" CSE, DCET Scanned with CamScanner Lintieal Repruserstotion . Althoug’y the Conouy neprusemtation ts Qpod for comple bi Ves sit te voarteful for mony sh. bry kas Mn addition » the rusertation suffers [porn the general, inadeg ramets of modes from the omiddle Of ie negpoe toe lwel number of these node. . These problems com be Overcome basi the we wh w linked heprssentation. These problems cam be overcome easily thaougly the use 6 ow linked Aeprtsemtation Ytacly node has thace fields s byt Child » data, and Taft Child [ia [es [BREE Gu) pa A 10 Scanned with CamScanner oot, @ rig Me © O68 © an ota Bee bil ® © Tes Trae Broan Thanesing reheat produc ov Wrvor ee uades i a Wee This Winton or de : ty, the trodes oe vise be weal. Where Kowosing 0 binany Hie > et csi anblias one Wzaked. in the + ipa ion Hak lft nalhcon. Pidepting the convention i Ten tos times One: LVR = ‘Gnondis: ““Fradecd RV - Postosdut Trawercel VLR - Preorder, Traverse: L honda fos moving, left » UA ia qa wing te node B toda pt. moving The mannss oor oki becuse 6} the position oh the V with vrupeck fe the L and R SUMRANA SIDDIQU Asst. Professor * SE, DcFT Scanned with CamScanner Jnesde, Thavenal celle fos. moving down the View Towanda The lat “Then Visiting tte rwede amd [hun moving Trwarels The left void inovdur ( sliuel mods. xnoot) ° if (root | = NuLD z inorder ( vool > lft Ciel) > print-t(" foc" » ob > data): 4 inordir ( root > rightChild ) 5 Thovdex + A/B *CXDTE Scanned with CamScanner Pres Thavosol Pruorda. Tronersal calle for visiting te rode first, the vioving down towards the amd finally Imoving dover tonarcle the sight Void procrdas (cliuek mode % nook) t if (vot | = NULL t prntt('% d's abot» dal) preordur ( root > Ltehalel 5 Preorder. ( yo0t > mgbrt Child D5 Prordes : + ¥/ABCDE Fruordes «1% PPE TO SUMRANA SIDDIQUI Asst. Proféssor CSE, CCI ~~ Scanned with CamScanner Foskrdu Thome Posterdir Thavereal alls for moving towards the >the moving dovory waht amd tho visiting ieee Void. pacord (liu mode x soot) down the bie towards the © Govt |= NULD © ecbesdia (woot —>lytChild) pestosda (avet > nighaChild)> print f(» mat vootr data)s 4 3 Postrrda : AB/CxDXE+ ed Scanned with CamScanner Lovelecdin Toone dn Leval occa. Tronescod viste the eet fick thew tk let child lorsee the nootd highs bh ao visi the ta a thi ones ck enol retvo lovel- porn te legtemost aa Fightraast mods - Level oxdix 2 +# EXD/CA B ante) nes aie Tnords 1 4251654 Pwordu : 1ar5seF Poston 2 TO 3942) Lovelovblee ;as4ser SUNRANA SIDDIQUI Asst. Professor . CSE, DCFT Scanned with CamScanner Fnample 4 : ({0) Trosdey : 3 J~64HFlOns ag (2 (5) Preovdes :19 1224675 WN ag G Ow Todds 36 7 4 Ba 5 ip © @ (3) Lewloidesr 210 1R 5 3 4 a6 1% Zaample 3 + (A) Tnoda: DBA EGCHFI ®) () Produ ABDCEGFHI © © & Pend: DBGEHTFCA Lodnda: ABC DEF ART Thorder + KG DLHMB AEC Preovder + ABDaAKHLMCE Poctordar + KG LMHDBECA luveloder : ABC DE @Hk LM Scanned with CamScanner ae Consliucting a Binanyp Thee fom the Thewersels | Steph: hook: for The fist |Last value im Pre Post wider, w ib & the root clement . tp: feaselv «the Savme element in Inerder Slip? tS the lft and right cubliten o the root - Slep3_ The values on the left of the rect im Snoraes Traversal become the lt bublbce Cements - p42 The value onthy % of the root in Snosdes Trowusal' beeome the 7 eublaze lemenl& Slp5 + Repeok the above stepe util the lee “lramplet : Comdruck 0 Benasy Tre fsern the follwing Tronversals- Ii : 5 678 lo HL IS a : 5s 7 4 ll j2 lo 12 8 6S fe aoe anode m Vostosdu ot , sia 7A 0 we In 4 [tou 2n@] wo [ps 671 Fi ta to (ay Fost Pot [6574] SURIRANA SIDDIQUI Asst. Proféssor ~~ CSE, PCFT Scanned with CamScanner e ® bm [56@\. (@n vt br [6 5 7) CIV 12 to] Fest (3) (*) 13 D © Th[6)e} [1 @) In Pest [65 J [i 2) fost tn Te id Post fed ml Peck (2) Q Binay ie, ree DO G) Scanned with CamScanner Trannple 2 2 Consliuedl a Binary Thee from the jpllewing ' 16 SF ae 6431 ay mie > (G4 J mn [6 +3] Poot Pst [8 4S 2] mn@8) ©@ G) Rest [8 4] SUMRANA sippiqy, 2.5 | Asst. Professor > “OSE, DCET Scanned with CamScanner Chane 2: Conick a Binary Ta fom he osng Tranverssole Thoda : 8 5 6 fo la Ih 15 Preorder : 10 5 8 6 Ih la Is Fink rode ‘m Poeordur vs lo as CRS i 15 th [a@c [ia @) ts] Tn m ped net, In [Ho] [id 1s J In Par [2b] [1a 16) Pre Br oid ©) 6) (a) = Binan The ®O® © SUMRANA SIDDIQUI Asst, Professor OSE, OCET ~ Scanned with CamScanner PROGRAM _TO IMPLEMENT TREE TRAVERSAL (INORDER, PREORDER, POSTORDER] Hinclude #include struct node int data; struct node *leftChil struct node *rightCh y struct node *root = NULL; ert(int); ‘uct node*); void inorder(struet node*); int main() t int i; int array{7] = {27, 14, 35, 10, 19, 31, 42}; for(i=0;i<7; i++) insert(array[i)); printf("BINARY TREE Elements are:\n"); for(i= 0; 1<7; i++) printf("%d\¢",array[il); printf("\n\nPREORDER TRAVERSAL: preorder(root); printf(""\n\nINORDER TRAVERSAL: inorder(root); print{(""\n\nPOSTORDER TRAVERSAL: postorder(root); return 0; 3 void insert(int data) struct node *tempNode = (struct node*) malloc(sizeof(struct node); struct node *current; struct node *parent; tempNode->data = data; tempNode->leftChild = NULL; tempNode->rightChild = NULL; if(root = NULL) Jhf tree is empty root = tempNode; else { current = root; Suan SIDDIQUI Asst. Professor Se, DCET Scanned with CamScanner parent = NULL} while(1) Jigo to left of the tree rrent->leftChild ULL) Hinsert to the left parent->leftChild = tempNode; return; } } else Iigo to right of the tree { current = current->rightChild; if(current = NULL) Hinsert to the right { parent->rightChild = tempNode; return; void preorder(struet node* root) printf("%d ",root->data); preorder(root->leftChild); preorder(root->rightChild); } } void inorder(struct node* root) { if(root != NULL) { inorder(root->leftChild); printi("%d ",root->data); inorder(root->rightChild); } 3 void postorder(struct node* root) { if(root != NULL) { Scanned with CamScanner postorder(root->leftChild); postorder(root->rightChild); print{("%d ", root->data); SUWRANA SIDDIQUI Asst. Professor * cr, DCRT Scanned with CamScanner Heaps Heaps aw Srgpontly wed To innplerwnt “prionitg Gps? Pricsilg gps Ib 0 in which the elemort te be deleteol i the one with highst (0% lowest) prio ‘lig. At livre , OW ehinert voit onbilany piosidg cam be insettid inle the gpeue - Definition of a. Maz Heap A aman. Comin) Fie ts 0 bee oo which the key value im tac mode ix mno Amalles (langes)) thay the key values in ik childnen Cif ann) Scanned with CamScanner —s Jnotion tnls 0. Max He Th detente the comet place fc the elorunt thad ie buena inserted » Use & © bubbl, ? process that: b ju at the nu mode of the ii Ped te ork, The elument ty be Insetted bibl up ay Qu te recosany to oneune & Ae in ‘nuenion. heap feed Process of Traestion § C1) Ynorease the heap Mose the no ] Suost the rv omar a te tnd 9} the Age by 15 bo that tb can/ Heap- The ue insortedl dara may err the properties of Heap es. it “Heapify? Scanned with CamScanner —> Deletion a Max H When am eloment: is ts be deleticl from a mace By Deen det . ize ty be Arslinclitred bp a. complete D Phoocess ulstion + © Riglace ‘ rect cand be died bp the last element Delete the last dlomont tom the Heap © bincr the last cbment i mow placed ab oe position mee ee met ra _ . itera last ened, place ain psn sual Lrarnple + Contudk 0. heap frthe fllnaing, valet: 7,165 4982555 3165 2,44 G2 D (2 ) _ 0 Sa Sod @ @ © @ woe © K® d d D © Q AQ - © © bdo 208 © @) @ mM B® © BD 6 OR® @ © aH © ®D Scanned with CamScanner M TO IMPLEMENT A MAX HEAP(INSERTION AND DELETION) PROGRA\ void heapify(int (J, int , int )s void deleteRoot(int [], int& )5 void printArray(int [], ind); int main() ke arr[] = { 10, 5,3, 2,435 int n = sizeof(arr) / sizeof(arr[0}); . print{("\nThe HEAP elements are:\n"); printArray(arr, n); printf("\n The HEAP after deleting root node:\n"); deleteRoot(arr, 1); printArray(arr, m); return 0; 3 void heapify(int arr{], int n, int i) { int largest = int temp; Fit Mieht= 241+ 1 r=2*i+2; M right = 2*i+ 2 if (arr[largest]) // If left cl is larger than root largest =|; if arr[largest]) // If right child is larger than largest so far largest =r; if (argest != i) // If largest is not root { temp=arr[ij; arrfiJ= arr[largest]; arrflargest|=temp; M Initialize largest as root heapify(arr, n, largest); // Recursively heapity the affected sub-tree } } void deleteRoot(int arr{], int &n) { int lastElement = arr{n - 1}; 1! Get the last element arr{0} =lastElement; 1 Replace root with last element n=n-J; // Decrease size of heap by 1 heapiyare, n, 0); //heapify the root node void printArray(int arr[], int n) for (int i= 0; i ane “K? with the iat che opal He rool? vhhew ad barely termmimalig successfully. 9f 6k? t lose than, Avets? kuy 5 then mo element in the ight sublize com have a key Value equal t “Kk”. Therefore , easel, the lft sublice of the nook: a4 SK? bs logon Scanned with CamScanner Dinortion inlaa Binany Aearehy Tree To inset o hey “hk? frat verify Hat the hag ia ; dippent prom those Of, existing pour bys the nce. Y the search & wre inset tHe, Pair ot the point the poarch terminated . () (4) (30) SUALNANA SIDDIQUI Asst. Professor * “CSF, CFT Scanned with CamScanner Delton fpom a Brrang Ararel Tree me a node from Binary Ktatehy Trae © the mode te be dolted is a af mode UW ts the dimplect cases inn this case , heploce the mode with the NULL amd fier the allocedeol ee tool Dee @) 60) @ O® & © OH & © & © @ ® dhe nods to be doletecl hoa only one clrte lace the ‘nocle with CT ae dae ei ee ded. Ral it with, NULL avd faethe allocated pace (69 + eleke\ fraps QD ©OaOHQ OH @) © & JB ne Scanned with CamScanner @) the mode te be deletéel has too chrilebun, RO) dhe_mode De Celle’ nas to Unluy luton the pair to be deleted le ino ‘cola mae thet hes two children >the pan te be is laced by cfthin the longest pais in i lift subi te 2 ee ile right eublie “Then proceed fo delete this replacing parr fiom the éuble fron whiel tt Me ested Dez GD) = GY lose 50 @5) @) Me lorraeat- pair im iE left © @O@ subbue with ae arses in ik right Subbue ge me SUMRANA SIDDIQUI Asst. Profes~ i Scanned with CamScanner “inample 4 le 4: Consbicet ae NW . PSN BsT pas IS Me 100, 73, $2 47.544 Scanned with CamScanner PROGRAM TO IMPLEMENT OPERATIONS ON BINARY SEARCH TREES #inelude #inelude struct node { int keys struct node “left, *right; struct node *newNode(int item) 11 Create a node { struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp; } struct node *searchNode(struct node *, int) ; void inorder(struct node *); struct node *insert(struct node *, int); struct node *minValueNode(struct node *); struct node *deleteNode(struct node *, int); int main { struct node *root = NULL; root = insert(root, 8); root = insert(root, 3); root = insert(root, 1); root = insert(root, 6); root = insert(root, 7); root = insert(root, 10); root = insert(root, 14); root = insert(root, 4); printf("After inserting:\n"); printf("Elements in the BINARY SEARCH TREE in their INORDER form: "); inorder(root); printf("\n\nAfter deleting 10\n' root = deleteNode(root, 10); inorder(root); printf("\n\nSearehing for 7..."); searchNode(root,7); printf("\n\nSearching for 4.. searchNode(root,4); printf("\n\nA fter deleting 6\n" root = deleteNode(root, 6); inorder(root); return 0; } » SUMRANA SIDDIQUI Asst. Professor“ ! CSE, DCET Scanned with CamScanner Void inorder(struct node *root) inorder Traversal { if (root if norder(root->left); printi("%d ", root->key); ULL) inorder(root>righ); 3 3 struct node *insert(struct node *node, int key) I Insert a node { if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node-left, key); else node->right return node; 3 struct node *minValueNode(struct node *node) { struct node *current = node; while (current && current->left != NULL) current = current->left; return current; } // Return a new node if the tree is empty insert(node->right, key); 1/ Find the inorder successor // Find the leftmost leaf struct node *deleteNode(struct node *root, int key) _// Deleting a node { if (root = NULL) return root; if (key < root->key) root->left = deleteNode(root-left, key); else if (key > root>key) root->right = deleteNode(root-right, key); else { if (root->left == NULL) /IAf the node is with only one child or no child struct node *temp = root->right; delete(root); return temp; } ‘else if (root->right == NULL) struct node *temp = root->left; Scanned with CamScanner delete(root); return temp; 3 struct node *temp = minValueNode(root>right); 1/1f the node has two children root->key = temp->key; // Place the inorder successor in position of the node to be deleted root->right = deleteNode(rootright, temp->key);_// Delete the inorder successor } return root; } struct node *searchNode(struct node *root, int key) { if (root = NULL) return NULL; if (key = root->key) printi("\nElement %d found in the BST" ,root->key); if (key< root->key) return searchNode(root->left,key); if (Key > root>key ) return searchNode(root-right,key); } Gumnata SIDDIQUI ‘Asst. Professor = bone OSE, DCET Scanned with CamScanner ‘cient Bineny Beasely Inees - AVL Trees | Yr 1962, Adeleon-Velekii and Landi inbioduced av brary bree Gliwelite thot % balanced wert the height tubliees «At the same times a rasa key carr be emliedl 61 deleted hoon buch a Gee time O(lognr) The rusting bia. hemacne heighit - balameed « This bax Miucliae is cabled om AVL Trees - Definition =P empl bree ts height - balanced fT a manemply ih wath tnd oI bad tight sublices respectively » then Tis height -balamesd. Hh (2) 7, amd Te ane height -balameeel . 2) |hi-hal £2 Le hol hp aoe the heighlz 1 and Tp » nespectively AVL Tree AN AvL Trt SUMRANA SIDDIQUI Asst. Professor" CSE, DCET Scanned with CamScanner Bolamer Faces - the “halamer facto.” BF(1)s fo node T in o bimany bie ined t be hi ha? howe hy and has respectively» vee the hetghas op the. Lift ama iad bubbien of T. Foamy awde Tin am AVL Kee BF(T)= -4,0,64.- | Be(T) = height of lebrsublia — hight of iit ou | Sa . A) 0 i \ © © ° © AVL a © Not am AVL The ee. SE AVL Rotations - To balance itself; » am AVL bie oy pergeron the following fou Kinde of votctions: ~ het Rotedion (LE) ~ Right Rotedion (RR) — Lift. Right Rotection (LR) — Rita Left Rotation CRED Scanned with CamScanner The bimt too votvtion are tingle puoletions anel, oe wo redodion ow © donble rotations”. > heft Refation - Yo ie Incase wnboalameset« when a do i ares ints the right cubbiie. 6 tre ” thon posfowrn a LL sotetion ie cublice » ae 3)! ny roan of Rotedion - Y a Ke becomes unloalanced » when w node i inserted inl the ft eubbiee of the et ioe thom pofiem a RR otntion. Pht RR Rotation nee SUMnANA SIDDIQUI __ .Asst. Professor "CSE, DCET ~~ Scanned with CamScanner 7 heft -Righrt Rotation ~ 8 1s a combination af, lept- rotation flawed. by right rotation “Gromple + A wode has beon ‘Inserted ina the He oublaee oh the subbire . Te vata c ee ed nook Purferm & LR Rotation - Pisfecrn felt the LL votection on the lept sublie of C- This makes A, the left oublize B. Node C is still unbalanced , however, wow it is beeamee oh the left -subbae of the lt sublete- Novo peefiem the RR relation on node B- This make Co tu Figfk cubbite of 16 own left sublize CO) Balannceel Thee ~” Scanned with CamScanner yy Regpat- Lift Ratton - Ue ts a. combinalisin of sight rotation folleredt by Lift otokion « “ample A ade has been inserteck ints the lat sublize of the aight cublbice This matte A, wn unbalanced avode. Fexferm a RL rotation - Peston fist the BR rotation on the subbree of A This makes Bthe right sublue of C- Node A ia stl wnbalamced » becuse oh the sight Sublice 6} ib agit Sublize - Now pac the LL votztion This maka A the subliee of ik right cublin B&B. “it 4 vi Baloneed Thee SUMRANA SIDDIQU! «Asst. Professor Hs 7 OSB, DCET Scanned with CamScanner Yrsertion nl w AVL Tree 6 Yasenkin im AVL Troe & perfromed ‘mm the bare wag as ib 1s porfemed ‘mn a binary 4 easel Vier - he mow orvode added inls AVL bie 04 the mode. Howevers tt nay lead te violation tn AVL Bren propesl omel therefore the hie mag or alo D alamee app notations « Rotation ts Aula pa node “u distwbed upon | ‘ineodeng the ool othenoise the vetnion is not regploed . Laampe ore n AVL Hit § 6304914 ,9F 218 9108 Sash a “OQ, Scanned with CamScanner Deletion pom am AVL Tree De a from am AVL bie is similar to thot ino binasy bearely biee » Deletion disturb an AVL lie and the ber the bie meds to be nebalanced in wd to maivctain, the AVL propertics Tnample + Deutz the nodes $10,155 14 24psom the Jollawing AVL Thee - Det (10) Scanned with CamScanner _ De (a!) . © Lreample 4+ Comsbivet am AVL Thee wing nods D +8) qa £3) ya Ee Oe ly LL es _—_—_ 4 Oo Scanned with CamScanner trample 2 Coelmaek am AVL Tree $1417, 57,9554, 1312,8, 5 IW, @ © IO) a de OR Bo ——_ o Ter? Scanned with CamScanner Scanned with CamScanner + DOW OAs. Professor “CSE, DCET Scanned with CamScanner Snormple 3 + Deutz @) fpom the following AVL bre (5) B® eq @a@ O © © @ @ Scanned with CamScanner PLEMENT OPERAT! Hinclude #include struct Node // Create Node struct Node *right; int height; i int height(struct Node *N)// Calculate height { if (N= NULL) return 0; return N->height; } int max(int a, int b) { return (a> b) 2a: by 4 struct Node *newNode(int key) // Create a node { struct Node *node = (struct Node *) malloc(sizeof(struct Node)); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; return (node); } struct Node *rightRotate(struet Node *y) // Right rotate { struct Node *x = y->left; struct Node *T2= x->right; x->right =y; yoleft y->height = max(height(y->left), height(y->right)) + 1; x>height = max(height(x->left), height(x->right)) +1; return x; struct Node *leftRotate(struet Node *x) // Left rotate { struct Node *y = x->right; struct Node *T2= y->left; yoleft = x; ON AVL TREES JAA SIDDIQUI J : Asst. Professor (CSE, DCET Scanned with CamScanner x->right x>height = max(height(x-left), height(x->right)) + 15 y->height = max(height(y->lef®), height(y->right)) + 1; return y 3 int getBalance(struct Node *N) { if (N == NULL) return 0; return height(N->leff) - height(N->right); } struct Node *insertNode(struct Node *node, int key)// Insert node { 1/ Find the correct position to insertNode the node and insertNode it if (node == NULL) return (newNode(key)); if (key key) node->left = insertNode(node-left, key); else if (key > node->key) node->right = insertNode(node->right, key); else return node; 1/ Update the balance factor of each node and Balance the tree node->height = 1 + max(height(node->left),height(node>right)); int balance = getBalance(node); if (balance > 1 && key left->key) return rightRotate(node); if (balance <-1 && key > node->right->key) return leftRotate(node); if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } if (balance <-1 && key right->key) { node->right = rightRotate(node->right); return leftRotate(node); } return node; 3 struct Node *minValueNode(struet Node *node) { struct Node “current while (current>left current = eurrent->left; return current; } Scanned with CamScanner struct Node *deleteNode(struct Node *root, int key)// Delete a nodes { ind the node and delete it if (root = NULL) return root; if (key < root->key) root-left = deleteNode(root->teft, key); else if (key > root->key) root>right = deleteNode(root->right, key); else { if ((root->left == NULL) || (root->right == NULL) { struct Node *temy if (temp = NULL) { temp = root; root = NULL; } else *root = *temp, delete(temp); 3 else { struct Node *temp = minValueNode(root>right); root->key = temp->key; root->right = deleteNode(root-right, temp->key); } root->left ? root->left : root->right; 3 if (root = NULL) return root; 1 Update the balance factor of each node and Balance the tree root->height = 1 + max(height(root>left),height(root->right)); int balance = getBalance(root); if (balance > 1 && getBalance(root-left) >= 0) return rightRotate(root); if (balance > 1 && getBalance(root>left) < 0) { root->left = leftRotate(root-left); return rightRotate(root); } if (balance <-1 && getBalance(root->right) <=0) return leftRotate(root); if (balance <-1 && getBalance(root->right) > 0) { root->right = rightRotate(root>right); return leftRotate(root); } return root; } SUMRANA SIDDIQUI ‘. st. Professor CSE, DCET Scanned with CamScanner 1S void printPreOrder(struct Node *root)// Print the tree { if (root != NULL) { printf("%d ", root->key); printPreOrder(root->left); printPreOrder(root-> } } int main) { struct Node *root = NULL; insertNode(root, 2); insertNode(root, 1); insertNode(root, 7); root = insertNode(root, 4); sertNode(root, 5); sertNode(root, 3); sertNode(root, 8); "ys roo printf("\nAVL TREES: printPreOrder(root); root = deleteNode(root, 3); printf("\n\nAFTER DELETION: \n"); printPreOrder(root); return 0; } Scanned with CamScanner

You might also like