0% found this document useful (0 votes)
39 views

DS Notes Unit 4.1 Tree

Data structure Using C Notes

Uploaded by

akshatvats999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
39 views

DS Notes Unit 4.1 Tree

Data structure Using C Notes

Uploaded by

akshatvats999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 44
an ~ Tree ts a von Linear DalaStwiebive called a tree, TIE isa Hierarchical vepresentakion of Dale. Tree is a dose Gructure which Wows you to ancciake a foavent Auld vdoordup b/o wri pieces of dale and thus ablows 1s do arrange cure an dake and pides in a Quteerchico Sorkin. Frorwaty atree cam be defined nrecurcAlvedy in the follooing Mowe - A Singhe vorle. by haelp is @ Tree. This node 14 also the woot Ok xhe Lace. 2. Subpose 4 ds a mode and Tht --- Tk Gvetreen labs weOLA MyM - We Veab. WE con Comaswet avers Aree by woking woe the pevedk of vedes Nom - = Mig, dn His : bree is dhe srk ond Th, Ta- - Tk ave She! Auls - Trees (ay oer &) = Foch Node hos ko be teacksble prom Bre oot Hewrg cnique Aequence arcs ,Colled @ pal. The number ofa on afath ts colied. the her of rhe path , The level aya ms ts the Length of the pelt He -ywot ty the msde pLsal. pohich ts Mee number 4) sda inthe path. The height 5 yon empty tree & the manimum Revel Of 0 node tn the tre A Smery tree is ether a baxtay empty OF U co i of Oo mode Coded: the woot coyelher talk boo binory Cotted Wt Lt Sub tree aval Tight Subtree ef He 1 ~ evminolagtes Usad € Nolen we with usethe term niede ; rather thon verter uote Sinory dee. Thats dhe moin Comporent uf any tree Abruckure, gure | Shows the Brwctore gf a ode (lee | SI Lap enind Pocrent ? The powent q arate Us ihe tmmedicke predecener of rede | nh Ais Khe parent ef Bc a Chill + The Crmmedkiote Succemors qo mode Ove Chiltol nodes A ChB eotich ts Bored oF dhe ap side is colled she LP Chidd omdchildh usdiich ws plocea a ( saght chitd . @ ava C acre the Jhisoh nodes of A. Root A Root ¢s Specialy dlenqnedtea! welieae bbe? Se ts amede voli Dros vo perent There Comoe only ene oesot ima bee, Ache Right Child D & tt Sei a ale oS, ee Se CN node. Node Db, E, F ove lead rods. " _Sttingys ‘= woles colt Some porent ave tlle siktinga D +E Cre Siblings. R 2@ Swovclh ay Gelge : gt is a Conneclhy Line b/ia hoo hod er toy = dg A ntole Con hove more tian one edge . A hos tus branes Toth !=) gock yuole! has to be rechable from He ywot Havugh O one Alquerce GMed path. the no edger tn A parr Us Caldeat pevarionr podt, . @ ve The level of a mode ts Ke no, of edges | hone Unugue BOK blu tk ama the aot, The lel a Hae went 8 cs dapined. rem. 43 a rode sat Level a T ren Ys Wid in ok evel land ibd: bovent a o& Level Lane A level 0 “a i level | Va /™% Revel D ie ee bbs 4 J (evel 3. The Leight yo woot” tree cs BO.e yatlivna Level of amode +1 un the free. The height a an Emply tree GS Zew. me height O&O tree fontaing a. Sige vote cs} We Dox +1 Prupertics of General Tree 1 Rwy node Com be the apot Of te tree ancl each node MW atree Kor se Pparty thok Shreve ts enocthy one pad Conneching dod vole ath Qrery ather vede cn Hebec a Goce webdle . re woot Dosa unique jsortet And every } edge comets a node sy UY ppavents - Threvefony O keee Unity AY vores bor N= 1 edges. Snowy “Tree A Binary tree T (5 defined ay a fev elements Called neces such Hat T ts empty folded “dhe wubl tree ov embly Aree b> comtaims 7A cL Hoguish mode R Cabal she Rot gy ir Lhe remaining nudlers of T Joom On ordared paleo cusgoin ‘oivery Tree Th and Ta , 3 fa) t Sulotvee “T Owd Ta Orve Cobted Left Aubtrec oF wipe Yep. OY Bre agree ef every mele 1 hers Haan or equal to 2 rom Khe tree ts Calted @ bivesy tee. Y Tis tonempr then Lawodt bs called re Let Auccersor of R why 1 Ta TS wonembky kun 1s work 4 Called re wiyis Ace emer aR, \ Pacherties cal tnogy Wee | — 1 Theme. of External viodes £6 | ynewe shamans TS °) Turevnod ores. (5 C049 yo dee Mok U 1a eee FEMCVING earternad yodearsithh Bheiy imtesnal pore One aire -.ax 6 Mme. Ar therend qf Bis procem evly the quot with Je dnao cotter nol! Grild sod remain - 3. The wo. uf enuternal nadie ts act Heart Kat where ig gre CRige of She tyees amb. most AQ, Tre [oder (retels Por 8 PULL “hinesy tree seal 19 atre cohrere Pnrer nal Aodos dom fur mex) Level _ Tre Mo. of indeamal” jrodes teat Ceprk Bard ePieiee| The Actel wo. of modes Ana bbthory ree: tsar Leart gh? ond amo ah si-) i tre hesghk & a4 A ino dree wlth w nodes as cl Least to nki Ond Os MO y, © Taqetelo Lele [a be ls ‘\cly antages 1 Data Ove Aleve catthout cmy ppoinle to UA Auceesson ov OnceAtor a. Any nade Com be Ceceried jxom aon other node be Coberloking Whe Orden , 3. Poromming Lowy uunge bohich clo not Aupport dy ncvaic yew WWeratieom jure only tris type ef representahion Jor a tree. bu. Sblictty , Disadventages i Povey meprerentedton ts mot Sudtible fer hewrol bmnexy dee ouk Ur ts only dead Sos Complet ¢ Bireay toce 2. Hewe weg Qf the Corvery Entries Ove empty te OMmeceroerAyomore memory ir Loasted! . 3. There ts . 3 Pts. Loy botttsle Upenhance the tree 4. Addiions amd dled ! CHous of noder ere inchicienk became Of He date movements on the carey, i To overcome ath there * r 7 re fpresentalton . mblems by using Lenkelh List 2. Link Rebwesentallon of Bmowy Tree ;— rife, i ryer Combe reprerentes Using clynanuie Premeny alocedii ng a ao nocle (n@ Linked Ciat form . tohich USCA Have ball ; vee orrreys ENFO lot, Right ard a Pointer Root 0 by ) | le J be aa ELSE mo ! “i Ela J me biel Adve 1, Smsentions dnd oleletions involves ro clata elemend Movemeyver 2. Me wastage of memory %. Emhancemens of Mhe tyee is botuibte | Drscdverbage \. Spoinkes Fteihs ave Cnvelved thick eCOUbY yore Apace thon dvar dala fielas, a. Lav rE Ming Long ages cabuch dle set ates Ogpnoornic memory AVocotion Nove Aifficulky ¢ drfphemerdhng Mee Smosy bree, “Types a Binoy Tree er ie. Drees & A ame tsa Binay toree q areal only a Ve 9x hos @ansot rede» tobuich MOH not Dove any Child nude = - Complete other | ene Comsider any Birory Tree T, ‘ Gath vende of T Con fovea most uso Chifelvere acéowelingly one Com Ahoud Had devel vol T Gam howe At moss A ries he Tate T Us Said tp be Comblete ¢ abl ues Levels ereepk Apotsbly Hho tort Rove morimun NO a] posible voces and CY OLL the modes ak He Rox Level appeor os toy deft od possible . ! . i, Seo tae Level | Neh, Ne 4 § 6 As va a a ee 4 Ie ne /\ Rive 5 i y hyde 21 2278 ae. 52 0 binary tree contains m voces ad level ©, ® Contain ot vnoat am vores at Level THI . Since m ivan tree Com Cemiain atwaat One node at level 0 i contain at mou af note at Level £ No. of voder at level o ts 2” =] Ree Se PG aa No " " 2 vs > ani ide Anja sia AD ty at Specikicay re Left Gnck aight Cnildyen of the Nocle K Ave ve Oak And Be K +I. enn Tre oy On Crclended binery tree «] Coch vede +O OF 2Childven. sn such core tre nodes with Ire Ove Called frlemnal nodes, amd the nodes witty doen one Called eMterral neces .. sometlynes She nodes jagremns Ry sing Cistle for Tnterrat _Trowersing | Binoy Tee i ee eres i As Tan List _ we woul Like bin te Oe andes Um pune tree: Tree teers jp the prmces ‘wy Gach wode on se bree © onée . | Trtoceresok ae Preordes. gi Process tre Root eo T cnatinese, SH unseee of RCW Pree * gg Suerne.g BOPP Cai Preorder (Root a Right ) Ab Sere no Aes Tnonder ( Ley Rort es oefe ai ¢ Eee Post onder { Ley Right ~~ SEER KTLREM (I ss een Traversal Agron using SHH Sue a ing tree rs | yrounttingl on Memory by Aome Linke wcacser dation “TEC Toto, Lop, Right, Root ) Preewes Tuovewal Using Steck" ap, preandes deversal alge. Gnee PTR + NoLL ,vekuern atep@ qalge. Jo) Proceed down He Left most pakh asroled Pa=Fk Ix) Rrvcess F Cahere ts mo wijid Child. No other node uo Processed Since f hos ne tet ould he) (Bactehraxing | Sop Hre top Clement NuLl Laon Aleck ard Sek PTR LA NULL . Since PTR= NOL the age. " CS Cowipleked , Ba Py Dyer Work hney Be! Ago Preordes (info, Left , Rent Riga) -_—— . . A Binasy tree TLS In memory The algo. clots a prteelar terovtrsol tT apblyng Om cpton Proce to eacngy OS nodes. An assray Gleck Ja Used bo Semforanity Lolel We gddnersld &| odes, e 1) WPnrtalty Quah Wad og onto ateck and iniilige Sex Top. =\) Shack {id >< Nol avd PTRi= Root | &) Repeok Steps % to 5 whit P7R 4 NULL 3) HPPLY prncers to Ywfol PARI fT Rygdd Chiiel’ ty Righs ¢ PTR) NULL Hen f Push on steak 3 Sek Tob + = Tet), And Stack Prop) = Righs Pr) S) Phe ehiibsl 1 ® LMCPTR) -4- MUU then Ste PIR, = Le L P18} Ure CPob Raom stack) se PP TR1 = Shack( TPT, ToP:=Top-) ¢ Games Eneider Troversal "~The tnowler traversal alge. ali uses a voertoble fointer PTR, which ux contain the fecadion of the node Currently boeing Aterned gro any Bleck , cohuch Lott hold Are adolwes cf modes for furore paece dong. | Age Smisialth Push Null onto Stock . amal then Sd PTR'= Root . Then appears He following aber ort Hull ts popped gum Steck, 9 Proceed. down the Leftynoat path swotedl al PTR , pushing £ach node Non to Aleck ond Alopping cohen a node N boitth ro Dept Ahidsl is pushed onto Aback b) TRacktrack) Pop and proocers the nocles on Slack. y NOLL 4» pobped y Hen emit. 9¢ Node n Gait aright chilel ACK) ts een - Act PTR = RIN). ape? st E Example A vie edi: hi i sae J Tnikally push Noll om fo Seek Steck ; ¢ Then Sek PTR =A jee Wot a T. 2. Proceed clown Hre Left most pat ~vwoted at PTR= fl , pushing A, 8,051, K onb Aleck , Stack + @54,8,D5 5% ; (Mo other nodes pushed onto Sock , ince K fas yo Le} Ch 3. [Bock droeking] The mode 5 tn, Daa bobed ond fornceeal leaving * stack: 5 A58 (tae Stab the proceming ak D, since oO for arecghit Chiboly Then Sek PTR =H, the wight chika afd. 4. Proceed dgon Me levy mot path woted at PTRoM, pushing the mole H onto Abeex and L Steck + G4 A,B, HL Co others ede ts purlred Onto Steck «Since L fosmodgt ; Ss TGocktweking) . The node L And V Gre pobpks and precesed Leaving Stack > AB Mae Qn Toveley(Tgo, Leph, Right Root ) A bingeyy bvedsadgitn enernesny . THis ep doers On inorler tomvessnd op Tt albphying an ope yatlor, Pmcers to Coch of 9 Nodes, AM Ory Slack ig vsed te tsemtemboromily hotel the daldrre Aven oY nodes , |. PRusth Nott onto dbeck and initialize Prey SHE Teh! = 1, glock tt := Now Arvo PTR: =Rovt - As Rebeok obits iol PIR NOLL ( Push Lop most fred Orko Stak) O) Set Top: = Top+) and Boek [Top] , = PAR Bo Se PTR: = le PIR] 3, Sek PIR: = Shack L Top? areal Tof! = Teb- ho Réptok Lielp S b61 pohile PTR He AWULL 5. PppY process bo Tinto LPTRY 6. C Right chill] 97 Right T PTRI NULL Hen A) Sek PTR >= AUghxt P7RI 6 fnoto skeba, a. Sak PTR r= = Stack Tob) ayol top Top-) Sxtk. Postowder Treever sal ———— ed In_ posterder WE Moy have to save a mode NX tn two diferent Attuakions , we diskingotsh blog the Awo Cored by pashing elthes N or Urs negative —N exito Seaek . Again Avartable PTR ws vd powch Contalrs the locatlor af the node N Mak ts curently pei NB Acavmesl . Trittally posh Noll onto Skeck Gna wey Set Pre. = Rook Then yepeat ve following Sep unkiL NULL ts pobpeal pom Sheek , 0 Pwoceect down the tet mart pal aveleol ak PTR. At eae mode Naf Hhe path, Push Ni onte-steck and GM jo: ; A aMyht Chit REMI» , push i ROM ombo deck on SMoek df NULL Ls popped s then emis. 4 a- negative node ts Pebbed Haat (s Yo PIR =-N front Aomné Rude Ny Aut PTR = N, Ova welt atep @) wy [Qnckt racldny’) Pop avvah proc ening bosidine node on | A wf ’ | prihii$ Ritu ‘1 | oD ze | / Gh HK Zoe kK Le Tnidolly push ult Ente Akeck and Sek PFR=A te To0k qT: Skeck ob a. Proceed dloon She Lek moss pad woted ai PTR=A posting bre viede A,B, D , LE onto Aleck . foather mare Since A has a ryt Chifel £ > push —C orto Aleck aftes fi pur before And p has aright Chill push -H onto AXOKK apres O pur bepere on, greek + > 5A, —C,®,D.-4) GK 3. TGockdeacking] Pop and fewcers K ad pob acvd bree Cy» Sice — Hts Megative only pep-H dnd leave Seek 2g A,- 6, B,D, H ie OM PTRi= 4, Resck PTR=H Aebtan Leb (@) s b PTR { 1. Proceed aloum Ae de most path as He onte Slack . Stee HL Ahad a “wit Chit M . push - onto a Oper 1 dost push onto Alok , Skack OA, = ¢, Bohs — ML % C Roekdaee king) Pob amd brecers L » Bub Ondy pop M , leave Steck + GQ, A, -C, 89H Nao PTR sicdds Nias PIR =M ood Retumn abel) 6. Proceed clown the Left mos Patt yooteal oct PTR=M Now mM (5 pushed onto Ateck -Twis Brees , A, —C, BHM { Berete dratieing 4 op @ra process yH4, 5B, Gd Oly Pop —¢. This Leaver Bed \ oA Now PTR: -C,Reagt PTR=C ard eM APE) Proceed down Ahe Lefkmorkt Pach woted ad PTR=€ -Movo C ts pushed endo atic anal then € Gack + gd A, GE 8. a (Backrsacki n5 fob amd orocess Bc, A. shen Noll tS Robbe, Shack u's empty avd de allgo 2) Completed Proceral K5m,2,™ ,H,9,8,6¢,A Nee Postoxtley ( Pnyfo , Lefty Right, Root ) A bivoay tree fis emphy Ts alg does a podtereley trveoressal 3 T applying an operacion Praxeas by each of iis nodes. AN Ov Sheek Cs Used to Temporarily hotel the odatse's oY nodes oe a Gy Creakion of Binesy Free Using Vraversals There axe. b0930 deperert ways oF Creating bincary tree Such as | Precrler amd enemler trevereats 2. Postowler and Browder traversal s Con Of Binary tree from Pyeomler cond spree Frere! Ston the Premmler sraversat From Left to Right “- Secon Zoe Acommecl Jocate ibs posthionr in crowler. toovergal Lek ro Atomned ode be x, 3. The node 9¢ beeordes Xn tnonder Prom UA Delt Aub tree And mod es Avec eadinng (t from aight Aubtace Ss Repeok Akely 1 40k Coch Aymbol nthe pecorler, SS). Preomles A eaDMEeEcr & Tnordlex DHREARFE CH 1 In Preorders trrwersal sept ts the Sixst node. @ 2. Now we Com Jind dhe viode GY left Aubstree ancl wight Aubtree tat imorder _ x LOaBeE A S ays A ley Righe DHE FCa Premdey Rone CP tes 3. Now She Hk Chita of He wot “vigde LU be the, Yer mode tn Jthe premdey Sequence. After wot node A te Qa Wy the wlgha Chillel Root: 05) k Lyieveley GOLK FHORG Vegi A Hoe) E Ls Novo Now 6 cs rot Neel. Oni aia EACKF HH OBS, ve Now & ts recat from Pree order EACKEHD B® 2 Crtokin A Binoy “Tete aor Podtcnder 4 Tronier treveral ‘s Scam Hhe podrondler traversal from Righs soley 2. For each ode Stomned Lotate il poston ininoder dea lek Mee Atowmned note oe. he node Worecedhing tm inorder y from dep 4 ‘ode anecediing Ue Rorm right Aulbvee Yo Stensers Hee @ soe Cea fi Tmowler Wee 2 CE OnFigd, ¢ eee rn Poshordes root os he Loxt note ® Sbree ore Svom Undrerler . ere Ofgcrat, ) , nA | from Imoder . upOre AF TCRGL fend, woste A EF © Kar a Biwony Seocsch Tree *- Seowching 0 Key or Qvale (HAN Ortlinar binary aree ts Vey Alo . This Ataaching chewalion Con Ine ide foxtey by Atortng Aho Valics tn dhe bowny tae in anodes py Vsing dhe bevy Aaweh wnethud to search Values, Binary a; Staxch Tree Pacpes Hes le A binerny Bearsch tee ves be embty .22 Lb iS mot empty then ik dabiaples He Pollo, braberties | Every Qlemend hora key, Key Cx) for element x fra ne two Cement hove the Aamne Ke a : 4 , he key (iy any) tn the Lept sutotree ove Amadler Hay tho Key im oot SMe Key CeL omy) tn the ret ubheee orre Larges Han Me Key in web ‘ i 4 The yt £ wiht sub trees are also benary Skerrch Tee % i &) % Opexmokions on RB STi . \ esehing enel Inserting GST + gubnse Tis a Blrory Seoosch Tree anh Om Then ay Lyormablon +s gen -Toperd she locaton of Trem tn the tot Alice eee T, OF Insert “Os ame voce in LH alplnepriake place én the tre , follors the Ydlowivg Akips. me. LXE Lith the yout nucle R of the ee 1. Convipor " , iy gy Teme Ro Payocersed Pave ceed Ps chidd eg iy 0g Trem 7 R tewntees ae qe. poor Aepll unt He Ing, i ; e i eee ot ee R such dat Teme R Which ircre te Adoweh ts Succemulld. err) rey | Cltmen Ww ors 1 sane tn Haris Care the starch cs » we meet an embhy Aubbec 1 in place ey Empty Aubtree Lvauce ergpial ond we Crdest Tle h tre T. oO Condider @ binowy Geawe U0) Suppo. ITEM = 87 1. Comborve Ere wale 87 with UO. Gna 19¢ pind 31 <4 rote fore \preceedh ko the Le Chit gf Yo 4 tobich!s32 Pe Rg with 32. Since 31732) Hrevefore prectediaeehe ight Chita of St wbuch 's 35 2. Compare She value 97 tothh 35 - Since 31735 therefore proceek doo He al gla chit .37, Trem et. Stavch ts Mirece sft. inde teol Ch Suppose Se Sellowing mombbess Gore tw caters inte an eniptty pinavy Agewch te . VR iver BABA Py) 2 ae" (aN rem <2 Ttem=a§% ( : I a, py. Exewcise Suppose the Jollovoing Leak af Uettews is tnsented Torley Jdko tnho an empty @ 8 T TROT we A BOW Fee. Bs To Pind am element Prom the &ST Find Cdnfe, Let, Right > Rout Liem, Loc, PAR) A vinowy Seawch tree T is in memory Cad Gn Them og oc Uy given . Tis praocedurve Pinds Hre location Loe of Ptem Avsl alto the lotadion PAR a} the Clemerd of Dtem, ther av tree Special Core; 1) Loc = NOLL anal PAR = Nurt Loilt indicate Hak He Lem not nT \O Loc #ODLL And PAR = NULL Will Ordicate Hrak Ttem is } Hye yout of T- 1) Lee =ADLL ana PAR ENOL WUL trebicabe Hod Clem csmei int end Con be bolded oT a achitd @ the rede 7 tot Rocakton PAR, oC Tree ts empty uy Root =NULL the: i OG: = fa} ond PAR: = n Se Cc. = NUL ood : J Ayal Me i $ =NOLL OY ( Ttem ah vot} Sf Them = aD at ythen Set Locr= Rovt Ard PAR: =u { Tmiddabige pointes PTR and Save 7 Of Tem < Info (Rout) Arey Sek PTR: = eA ERoot 2 @vol Save : = Roo} Edse iP; Sek PTA: = Rigid (Root andl Save: = Rew &. Rebead MS epeat Geps Sand 6 while Pre NULL fox). suppose woe delete Un nee Brom tHe tree 1. Mode Un bos no childern « tt Aah ee Root. ! oot yan | Tee t0 Arvest 3 2 {7 a F oie mas % (a) uf ee - e f ea) is Lat? , se ve Free tlie aan ONS > a . 3 A el, eel + geht? RE a1 al a ' het ye ! edt 2 A Yt Rokabion; — tlohen Nede ts added s adde R +0 Riad c ppt o Mad ne —— Sart vee a ¢ ® ° @ a ie - o bee 4 jue ley sunlbre Riga: Ro Rotadion a Node © Gog ii Eee seve e Rotadton tren Rig Rorektor- example Creake Om AVL hearth tree from Ihe ————e . y ca WT) T, BoA, Bits Pr yh Sot” oO —_——a tnsest H ) tnsest TL Tnsest J Insest @ Imsest A Tywiest Unbollomce Tysest K unbalance ;

You might also like