Tree Structures PDF
Document Details
Tags
Summary
This document covers tree structures, including their definitions, types, and properties. It explains different types of trees such as Binary Trees and Binary Search Trees and examples are provided.
Full Transcript
UNIT – IV TREE STRUCTURES 1. TREE ADT 2. BINARY TREE ADT 3. TREE TRAVERSALS 4. BINARY SEARCH TREES 5. AVL TREES 6. HEAPS 7. MULTIWAY SEARCH TREES. 1) TREE ADT: A tree data structure is a hierarchical structure that is used to represent and organize data in a wa...
UNIT – IV TREE STRUCTURES 1. TREE ADT 2. BINARY TREE ADT 3. TREE TRAVERSALS 4. BINARY SEARCH TREES 5. AVL TREES 6. HEAPS 7. MULTIWAY SEARCH TREES. 1) TREE ADT: A tree data structure is a hierarchical structure that is used to represent and organize data in a way that is easy to navigate and search. It is a collection of nodes that are connected by edges and has a hierarchical relationship between the nodes. It is a non-linear data structure. The topmost node of the tree is called the root, and the nodes below it are called the child nodes. Each node can have multiple child nodes, and these child nodes can also have their own child nodes, forming a recursive structure. EXAMPLE: noles moie i n i t e Gel or One (oo) i r e e i9 o oil of dhe o ef h hee a dhe nole i9 ds)qnaJel here one epesenrd me he emmining 1ee ard Jhe as Sib 1* Eoompe Tatee ADT CSLorICtOe Poot nt pmen ooh ( 1euell h i l a (B euel 2 nade Siblings O 3 Gubtaee J O } Ndee e o in d9iee DT 19 alll jent Root node uhich aoQGNot haN a rde nool noda. te A A 70ot hode he aboo t e e In S a IG l t o d Jole allod ocle Ee mont in h e Eah alato len 9 C hktnern alled callad hai a r ahi Ihich ongnot A Oco HI J , f G m aloo voe Jeor neoks Cou callod Srbling i_Sbicgs a drijd of Garno pvent S 3 Solings DE CEn Gibli In o aloo toe fG co H oaSibling9 w poth A uece of Conse Ctutie echo is cal loct pTh In he akoe tee, he a om he bot necle P 0 5 ucn as A and T viJargih dhe path AXmben ef ges in ahe pth is 3 osctepa om A i)Deee nimbo O onten Coo)alb tee of e 1 S qua Jo he node. h e cocR nocle ze ZONO The d e e of Vi)Dep #e deph o n s Bo Congth af Ha To any n l e n o he depth er ta eDL CnnueTt om i) tiegh arsle A #he nad o he oia numbe o the a beo is in t o hoe t2ighY ot he okepest nake ncle c0t paih oom Xnegto 1ocer ppEed dooae A aIIO 0 node on o n nde is any Anastor An o 'to al nde dhom ho pat an a na ces9 lotc rg doeg n halah any any Ona a annee ss 7 kK {7 he ot nole Pc nd Gi o a b o we, Tn D C e a n ade nooe onary de is ary GeA9 dlegcendan A 1ea} d e. node o poh oonm h e houe a y oeendants- nae does not he lea ndes QGJand k ome tee n be abolte olestendatS q nade A Binoey pee ADI DDeinition o e e in cohlch o Biroy dee l s a eolal t/pe made han i dhildna noe a n hao the Otha 15 Known ag Lejt hld a d n e chie) B Known a9 Right dhit ChibbreD o ) o e have cithe 0 a broy nee, Cl/ONY move than Chi den dhicten ahiloben at rot move han Iohid o») 2 teve Of Birwy nodeo a aoamUm um be o pree 9LO 2oot nodde elel O Leuel Numben node at CeLret 2 Leel 2 ). Leal 3 T9pe9 P o y Drce: coe e Seueal yp9 alBincy e blLOwing TRR Sbicty Binoy Snee. nodes tee in kDhth nee ls a brop Sticty Brcoy Childbers. so t a haS racty uo de except e one chla in any SreO Iee nee in hich aey Wee 9 a Pir SKEUD node ha9 ony one dhild ode Opl a co4 & ypes of Leu bee Thee SKeedBiy ree Let SKeued Biray Ire ight havedBor e a L nocle kth ony the 3H Chid. A B a e e ha9 nde Oith only the naht Chid. |re hoG a rre hih y ight SuLtres Subtee9 a Binoy Derope Biry pee T Binay pe ( ) A Bincoy t o beceme TUtl Bince inee al o n jaa noN-Jeal nde e Some i e and ard eNY n elY Coe al a ves two childstens umbe af a h29 ecotty mofimum paeibe numben COnt1an roUId nodes in aal aciS h s 8h+)-1 naces tree o heght A gu birny piee A) Complote Bray ha r a c y two ohild brt al Nade venon L3 at he Same Qve) Same t e l ROWeS neEAIAY noi oeig eves aao oree o r e lahre al A CompUte Birery to e laCt t2et numben anokeg except al exepi a maximunm hala /led om (0}t to trom e?t to Qe dlomentS 2ed Ia9t n he naht NeC ReprgnICtion o Birrony i) 0 epaeAeM ha B n nce hene Ce uayg They ovne2 epreRHIte) o Geauent)a do) Linaan (oo) Aeony Binony Gree of Biay bee * lintcod noprentatHon Repne9entolton Cohony (b) incm sing Sirgu nepprecened Ging Sirga a) Squental comens ae epecenico he He oayg. dimeNIiora iH the Gbred Co) One. u DM ke oce Tet of h e The Chment n poSiio rn T ary postion 0 s al hid po9ition.oi+1 The togt i is a dhild o (/9). The 9igh in pasition oris pcvreni eeay 2 PEpRECENTEroN 35 3 12 OF I7 BNRey TPUE 16 18 i n l c e epreeniahn ol 2 Pinay o r IepN2aent 5 HS The etonmens e oo zieldg. a CSig poinkos eprraeNtAtoN inid node In he aoh to de ß l Subtwe poinc Dala iod bte. ponten o e niqht Doba Linkad nepRTOntd uing S Binmyo RghH Dua Child Chl oblobeegS oldotegsS Linked Representation of Tree Data structure Operation on binary Treee: i) Creation: ii) Insertion iii) Deletion iv) Tree Traversal i) Creation: The idea is to first create the root node of the given tree, then recursively create the left and the right child for each parent node. class TreeNode: def __init__(self, data): self.info = data self.left = None self.right = None def create(): data = int(input("\nEnter data to be inserted or type -1 for no insertion : ")) if data == -1: return None tree = TreeNode(data) print("Enter left child of : " + str(data)) tree.left = create() print("Enter right child of : " + str(data)) tree.right = create() return tree ii) Insertion: Given a binary tree and a key, insert the key into the binary tree at the first position available in level order. The idea is to do an iterative level order traversal of the given tree using queue. If we find a node whose left child is empty, we make a new key as the left child of the node. Else if we find a node whose right child is empty, we make the new key as the right child. We keep traversing the tree until we find a node whose either left or right child is empty. def insert_node(root, key): if not root: return Node(key) else: queue = [root] while queue: temp = queue.pop(0) if not temp.left: temp.left = Node(key) break else: queue.append(temp.left) if not temp.right: temp.right = Node(key) break else: queue.append(temp.right) return root iii) Deletion: Given a binary tree, delete a node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with the last element. def delete_node(root, key): if not root: return root if root.val == key: if not root.left: return root.right elif not root.right: return root.left else: temp = root.right while temp.left: temp = temp.left root.val = temp.val root.right = delete_node(root.right, temp.val) root.left = delete_node(root.left, key) root.right = delete_node(root.right, key) return root iv) Searching: This operation find any particular key value is present in the tree or not. def search_node(root, key): if not root: return False if root.val == key: return True left = search_node(root.left, key) right = search_node(root.right, key) return left or right k. hiermdn oloa Suttun0 ho is a a t teee.. inTy in aha in foom ol fom ol KOhn uhan O3gpmzeg epIient S Serhira hirg, hat fsTICient Syem be ud i t me OrC on Paaes Cgarnize ea dhe Cocip comp Ue Okanpus rtcte is C p pn nid t o Some nac Document Cbja /xnAL HTL The CocsuG 1U ihe fm obee ompb C o n p i l a i H o n t o ne o p NG TG40 nd pese i n d e ch c httahkoee s CIficicnil inde t US r c s Ceu orn drlma o ol Ches Narb d e - - i n t t - (solldata) Seyf loft- No Sels ight -None Get oata: daia we initiaira o the ede ho, cro e d d Bire nco niado Co) Orl hlccb (344) nco f t cC g t tbde G a metlard fs 1/tim al ts P90e toen On. to ter ty Plooles n Jechiaues tomso 3types fhee he PoOnes T9xaehga e a arle malens Onokn hoeso tedanal S alGo calltd asyomeric bolea odon The n e omd GlG c ic o Thc CLOdi in o n Cicle PeCi Subrea n betuecn ho o1 O2d 2g h nada iS ocG Kmon a5 1S 1 B n. Cdo algoi hm e Iroocle t ib bee O) 19Da1orse u e o t narb ond finey vig to ubhee emae 9990 tio 2ght olet incalo 1nitemcal (GeH,ocot 300t geif. in0e(rJehso (ot g t 9 oppero) 05DeG- gef ineacls 9rotessey vot, ight oetton 2S - H,1 ,ce Snpcen G,DLBE, 9 BDA,E, K a n d proctio I n c d talsay GueSi 5,15 18, 20,25, 30,3540 H5,50,&o ) p egpde oenc sire c o t nece is DolEN, to Orco In pat dild hoodes cluld are ight peformio befoe kel hatensu bincey be The pewoes in prndla e 3 t Sbbpee ACene SUbve in pieoxes Tananse e ht peocoriltnsa (SeH,0L). de -[J 200t. pprd (vwct daia) raitr (7wobk) e5 es+ Set. pecacles (rooc-3right) lte + S i f preodis (50 B, DG, Hy LE, C paedilo batehs FTJ K 30,20, 16 518,25, AB,D, C h 3550,uS,60. F,6 H,2 Post orctos balesSr Poslolon tolorje G, L, H,D, E, 516, 15 25/20 T,K,3 FC, A D,B, 4,I,6,F 35, 4Go,50 ho30 E, CA kefove tPO kefoe taltnies he 1s a l u n Te.Jo and 00E had 3 D O -h h oo 9ight Subbes Ceyo wo da Ood 1bt in pas acla rea TRA t EYE and 7ght Clb accesGed af knoun a s LRN kroun LRN as iS s aso Cuclon agoailhm pOs pos Nocu) (Lf1-eghi- vecu19h 1y aloitn penfosmetd cODendosmed Opoa ons Tho fotouig Ot cach rode Conse ho Pit b l e 19na pratonse Right Fiaty olct podoicla12naternsa (soaDot) Pastodasi)ma\derngci (onot- Ut) eg: Se e8-aprard (not-daa) Program for Binary Search Tree: Operations: i) Creation ii) Insertion iii) Deletion iv) Searching i) Creation: class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None ii) Insertion: def insert(self, value): if self.root is None: self.root = Node(value) else: self._insert_recursive(self.root, value) def _insert_recursive(self, node, value): if value < node.value: if node.left is None: node.left = Node(value) else: self._insert_recursive(node.left, value) elif value > node.value: if node.right is None: node.right = Node(value) else: self._insert_recursive(node.right, value) iii) DELETION: def delete(self, value): self.root = self._delete_recursive(self.root, value) def _delete_recursive(self, node, value): if node is None: return node if value < node.value: node.left = self._delete_recursive(node.left, value) elif value > node.value: node.right = self._delete_recursive(node.right, value) else: if node.left is None: return node.right elif node.right is None: return node.left min_node = self._find_min(node.right) node.value = min_node.value node.right = self._delete_recursive(node.right, min_node.value) return node IV) Searching: def search(self, value): return self._search_recursive(self.root, value) def _search_recursive(self, node, value): if node is None or node.value == value: return node if value < node.value: return self._search_recursive(node.left, value) else: return self._search_recursive(node.right, value) Nulti-way Sanch tsootint Denitioni Santh as m-wy toeo. gonsnaliyd Vouen bnay M-way ear ch The g onsttan on on an )Each nodo n the eoo can as ocicle twith chldson and (m-13 key atde Esample m- ley chetzbeen ?2/? ?/? ’mme mchldren The oe Koys in an node the aDLanged Fxample : the poit k chi ldren dos than tre key thu node V) The koy un the Aaut Cm-) Chidon highey than + By ang tree, tho weanch and pdate opnatbns much MoO yaant 2030 36 20K