You are on page 1of 31
6.8 Binary Search Trees ‘An important application of binary trees is their use in searching. This structure enables one to search for and find an element with an average running time O(log,7). It also enables one toeasily insert and delete elements. A binary tree T is termed as binary search tree (or binary sorted tree) if each node n of T satisfies the following property: s Using C eater than the values of all nodes i its left (AL subtree ang eThe value at n is She value at » is fess than the values of all nodes in its right suby fe tree shown in Figure 6.21 satisfies the binary search property 6.28 % Data Struct For example, th Figure 6.21 Binary search tree sumes that all the node values ae dsin inary search tree given here ass tree which admits duplicates, thats ‘There is analogous definition of binary search which each node 7 has the following property ‘e-The value at mis greater than every val 1s than or equal to every val ‘The definition of abi ue in the left subtree of mand ue in the right subtree of f@ The value at mis les simplicity, we wi perations on any binary search tree. For teger type. follows: Now let us discuss possible o assume thatthe value of each node is int “The structure ofthe binary search tree is a8 struct node intinfo; struct node * left; struct node * right k typedef struct node” bstnode; Routine to make an empty tree pstnode MakeEmpty(bstnode t) if(t!= NULL) f MakeEmpty(tiet Trees # 6.29 MakeEmpty(t->right), free (t); ym NULL: k so operation for Bina Seah tee stnode fndint x, bstnode t if(t== NULL) return NULL; if (e info) return find (x, t-> left); else if (>t info) return find (x, t-> right); ese return ) ‘ndvfin) and FindMax() are two routines which return the position of the smallest and Ingest node value in the tree respectively. recursive implementation of FindMin bstnode FindMin(bstnodet) { if(t>left == NULL) return t else retum FindMin(t>left) } Non recursive implementation of FindMax i FindMax(bstnode t) if(t!= NULL) while (t>right = NULL) t= toright; return t, 6.30 % Data Structures Using C 6.8.1 Insert “The insertion operation ona binary search tree is simple. To insert is simple, To inser x into tree an a nesting from the rot node Weis found, do nothing otherwise rcPapat on the path traversed. Duplicates can be handled by keeping an one extra egos rode record indicating the frequency of occurrence. Figure 6.22 shows a typical ex example insertion of one node to a binary search tree. Figure 6.22 Binary search trees before and after inserting 15 6.8.2 Delete sarch tree is to delete any node from ‘Another frequently used operation on a binary se ation given which has to be deleted ‘Suppose Z'is a binary search tree and,xisthe inform: Tift ivexists in the tree. Once we have found the node to be deleted, we need to cons several possibilities. 'e Ifthe node is a leaf node, it can be deleted immediately. # Ifthe node has one. child, the node can be deleted after its parent adjusts a pois to bypass the node, @ ifthe node has two children, the strategy isto place the data ofthis node witht rsively delete that node. smallest data of the right subtree and recut feletion of node from a binary search tree. “igure 6.23 and 6. .24 shows di 22, 2 “a Gx ® @& a i ® b x (43) A Figure 6.23 Deletion ofa node (14) with one child, before andafier de Ud withone Trees *® 631 Figure 6.24 Deletion of a node (12) with two children, before and after Seale 6.8.3 Efficiency of Binary Search Tree operations Aswe have already seen, the time required to search a bine O(n)and O(log n), depending on the structure of the tree. The structure of the tree depending, onthe order in which the nodes are inserted on the tree. If the records are inserted in sorted (orreverse) order, the resulting tree contains all NULL left (or right) links, so that the tree search reduced to a sequential search. If the nodes are inserted so that half the nodes inserted after any given node with keys greater than k, a balanced tree is achieved in which spproximately log n key comparison are sufficient to retrieve the element. ary search tree varies between Trees 649 Greation of BST and cifferent traversal r EC a int ‘eidBuilTree( Tree “int oid Teainorder(Tree*), void TrevPreorder(Tree *), void TravPostorder(Tree*); vyoid main) { crs); print \nenterthe values") scanf'%", 8X), root=(Tree*)melloe(sizeot( Tree) ro9t-info = x . rootleft= NULL: root-right= NULL: print ‘nenter the values "2toterminate\") \while(scanf('%c", 8x) = EOF) BuldTree(ro0tx); pit") pent ininordern), Tratnorder(00) vin \xpreordern’) TravPrearde( oo print 'npostorder’); TravPostorde(-o) } Pain ends“ Tree ‘new_node: if number node->info) NULL) if node->rig ew rodes(Tree"ymaboctszeo ree): rnew_node-info= number, rnew_node->eft = NULL; rnew_node->right= NULL; rnode-right = new_node; } else BulldTree(node->right number: } else { if(owmberlef'== NULL) { new node=(Treetmalloo(szeot(Tree)) rnew_node-info = number, rnew_node->left= NULL; rnew_node-right= NULL; node->left =new_node; else ‘uildTree(node->lef number) else. printf"\nduplicate number = din’ number; 1 bul ee tint eds void TravinorderTree node) if(node != NULL) ‘Travinorder(node-ief); print'hd “node info) Travinorde(node>righ); pretest) { pipode NULL) pid “node->inf) i Preorder(node-ef); Te \preotder(node=right}, } voi 7 { ypode I NULL) ‘ravPostorder(node-let); ‘TravPostorder(node-right); print(%6d ",node->info) revostorder(Tree “node) enterthe values 8 cnterthe values *zto terminate @28Sisten iter 11 22 33 44 55 60 66 7 88 99 reader 98.85 44 22 1 133 60 88 77 99 Pesoder i 33.22 44 60 55 77 99 88 66 6.10 Height Balance : AVL Tree The method for achieving the goal of balanced tree was described in 1962 by two Russian mathematicians, GM. ADE’SON - VEL’SKII and E.M. LANDIS and the resulting binary search trees are called AVL trees in their honor. AVL trees achieve the goal that searches, insertions and deletions in a tree with 7 node can all be achieved in time that of O(log 7 ), even in the worst case. The height of an AVL tree with 7 nodes can never exceed 1.44 log”, and thus even in the worst case, the behaviour of an AVL tree could not be much below that of a random binary search tree. In almost all cases, the actual length of a search is very nearly log and approximates that of the completely balanced binary search tree. rely balanced tree, the lef and Tess ® 651 com ugh we can not alway i subtrees of any nodk hous! ys achieve this le would have the same cn as sure thatthe heights of every left Boal, by build a al 1B search tree we snd righ ses eerie morn * tree is height balanced. fis a non-emy tre, then is height balanced if z,and T, are height balanced and resi ve Ply binary tree with 7, and 7, as its left iret 0 ‘a f,and hy, ate the heights of 7, and 7, respectively. 1 , at iSnary ee requires that every subred also be height Cea jh hel Sts wine salinded factor, BPD, of anode Tins binary tree i defined tobe f= where hand rhe eis ofthe left and right subres of 7, For any nde nan AVL tree BPD) 24,0001. sie isa binary search ree where the eight ofthe righ sabre andthe left subtree avy amos | andthe eft and right sures ar aanin_ AVL eft is exceeding the sf Nye ebalancing hes ob an place, After each insertion nd etetion of ems if uk nce facor of any node exceds he vale Then rebalancing ofthe eis cared ot ere erent rotations. These ations ae characterized by the nearest ancestor of the rewly inserted node whose balance factor has becomes + 2. ‘there are 4 types of rotation. i) LLRotation i) RRRotation ii) LR Rotation iv) RLRotation ‘ULRotation: itis used when the new: node is inserted inthe let subtree of let subtree of anode A. Figure 6.26 shows LL rotation, Balanced _ Unbalanced Rotation type subtree following insertion ® @ ® ® 6, GF SO © © Rebalanced subtree © 6.58 % Data Structures Using C (b) Balanced subtree Unbalanced following insertion Rotation type Rebalanced subi 8 A, ; ; A nh oneg—the hee jt B,| | AI Height of 8 increases toheight +1 Heightofsubirees of B remainh+1 © Figure 6.26 LL Rotations Ay RR Rotation: It is used when the new nodes inserted in the right subtree of right subtree of anode A. Figure 6.27 shows RR rotation. Balanced Unbalanced Rotation type Rebalanoed subtree following insertion subtee aad (a) height he2 B) |B, (b) Balanced subtree balanced following insertion Rotation type Rebalanced subtree @) " RR height 7 shee Height of B, increases toh +1 Height of subtrees of B remainh + 4 aaa Figure 6.27 RR Rotations 4H) LR Rotation: It is used when the new ‘node is inserted in the right subtree of left subtree ‘fanode A. Figure 6.28 shows LR rotation mice Unbalanced Rotation type Rebalanced = insertion subtree 6.60 * Data Structures Using C | (0) Bolanced svoee Unbalanced following insertion Rotation Pe Rebalanced subies > @ B Ap 3 8, c] [ce © Unbencedtoowngnseion _Reaton ype Rebdenost ste 2 x > on @) Figure 6.28 LR Rotations Trees # 66 used wien the new node is inserted igure 6.29 shows RL rotation he left subtree of right subtree jenced —-_Unbalanoed Bak Rotation ype ree following insertion ee & RL Rua) q 8 ] ns o c me &]I | : | P] fey] (b) Balanced subtree tee iced following insertion Rotation type Rebalanced sut te RL(b) 6.62 # Data Structures Using C = RL(C) 3 : @ Figure 6.29 RL Rotation 2) 6.10.1 Insertion of a node We can insert a new node into an AVL tree by first using the usual binary tree ins algorithm, comparing the key ofthe new node with that in the oot, and inserting hp rode into the left or right subtree as appropriate. It often turns out thatthe new node can, inserted without changing the height ofthe subtree, in which case neither the height nrg balance ofthe root will be changed. Even when the height of subtree does increas, itay be shorter that has grown, so that only the balance factor ofthe root will change, Thea case that can cause difficulty occurs when the new node is added to a subtree of then thatis strictly taller than the other subtree, and the height is increased. This would cance subtree to have height 2 more than the other, whereas the AVL condition is thatthe ig difference is never more than 1. Let us explain the insertion operation with the hp followingexample. Insertion of following nodes in an AVL tree 155,66, 77,15, 11,33, 22,35,25,44, 88, 99 ‘New ‘After insertion | Rotation ‘After rebalancra Identifier| (55 Norebatancing nee. @ Norebalancing ret! (66 ® Trees * 6.63 am S fa @ @ “© ® ws Norrebalancing needed ® ©) wt @ QO O-4 K& PO (w)33- @ ® © ®'@® @ 6.64 Data Structures Using C Norebalanng Neg (waj22 Norebalacing nai (09)25 | cage Norebalancing needed 6.66 # Data Structures Using C Insertion of following node AVL tree jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec new | Aterinsertion Rotation] ‘Afr rebalancng (jan No rebalancing esis (ifeb @® No rebalancing neeey (iiymar Q "No rebalancing needeg © © (wyape @ No rebalancing needed @ ©@ @ (may Norebelancingneedeé @ ® @ @ @ Trees ® 6.67 wr | Norebalancing needed C a Norebalancing needed ibang Q @ @ @ OVO © "No rebalancing needed He 4 6.68 % Data Structures Using C (w) oct (xi)nov (xi dec No rebalancing needed ail Trees ® 6.69 gent! ‘AVLtree implementation using linked lst [a eee al snclude structnode { intinfo: intheight, struct node “lft; struct node “right, k typedef struct node “avinode; avinode LLRotation(avinode); ‘avinode LRRotation(avinode); inode RRRotation(avinode); ‘avinode RLRotation(avinode); avinode Insert(avinode, int); oid InorderTraversal(avinode); void PreorderTraversal(avinode); void PostorderTraversal(avinode); static int Height(avinode); int Mann, int); voiding) ( avinode t; int x; char ch = 1", t= NULL; cts); while (ch != '3') ( printf(‘\n 4 -INSERT"); Print(’n2- TRAVERSAL’), printf(n 3- QUIT); print"\n\nEnter your choice:"); ffush(stdin); ch =getchar(); 6.20 # Data Structures Using C 6 Dons Cinge sswitch(ch) { case ‘1 print nenter the element to beinserted”): scantt'%d" 8X): = Insert(t.x); break; case ‘2° print tnintnorder Traversal): InorderTraversalt); print‘ininPreorder Traversal): PreorderTraversai() print ninPostrder Traversal": PostorderTraversaXt), break; case's break; defauit print rong choice! Try agi”): ? static int Height(avinoge t) if(t== NULL) return=1 else return height } avinode Inserttavinode tints) it(t== NULL) inode) malloc(sizeot{struct node), NULL) print(-\nout of memary space") else : ee teinfo: ‘teheight = 0; teleft = t>right = NULL; 7 } ose it(xlettx); if Height(t->left -Height(>right if xinfo) LRotaton(t); else t= LRRotation(t); } else if (> teinfo) { toright = Insert(->right x) if (Height(t->right - Height(t>lef) if (x> bright info) t= RRRotation(t) else t=RLRotation(); } toheight=Max(Height(+->leR) Height t>right) +1 retumt, } ‘anode LLRolation(avinode node) { avinode temp; temp=node-left node->left= terp->right; temp->right= node; node->height = Max(Height(node->left) Heightinode->right) * fi tempheight= Max(Heighttemp-le,rode-nelght) * 1: return temp; 1 6.72. # Data Structures Using C { node-left= RRRotation(node->le) retum LLRotation(node); ) avinode RRRolation(avinode node) { avinode temp; temp=node->right, rnode->right= temp->left, temp-lett= node; node->height = Max(Height(node->le) Height(node->rght) +; temp->height= Max(node->height Heighttemp->right) + retum temp, } avinode RLRotation(avinode node) { node->right= LLRotation(node-right); retum RRRotation(node); } int Max(int x, int y) { itoey) return x; else return y; } void InorderTraversal(avinode ) { if(t}=NULL) { InorderTraversal(>lef); printf('%d* t>info); InorderTraversaltt>right) Trees #673 a PrcrderTraversaliavinde ) { gquenuuy printf('%d" info); PreorderTraversal(et) PreorderTraversal(-right) } eid PostorderTraversalfavinodet) if(t=sNULL) PostorderTraversal(ef PostorderTraversal(tright) printf%, info} 4-INSERT 2- TRAVERSAL 3-QUIT Enter your choice:1 Enter the element to be inserted:50 4 INSERT 2- TRAVERSAL 3-QUIT Enter your choice:1 Enter the element to be inserted:60 1-INSERT 2- TRAVERSAL 3-QUIT Enter your choice: Enter the element to be inserted:40 1 -INSERT 2- TRAVERSAL 3-QUIT Contd, 6.14 # Data Structures Using C Enter your choice:t ~~ Enter the element to be inserted:30 4 INSERT 2- TRAVERSAL 3-QUIT Enter your choice: Enter the element to be inserted:70 41-INSERT 2- TRAVERSAL 3-QUIT Enter your choice:1 Enter the element tobe inserted:80 4-INSERT 2- TRAVERSAL 3-QUIT Enter your choice:1 Enter the element tobe inserted: 90 1 INSERT 2- TRAVERSAL 3-QUIT Enter your choice:t Enter the element tobe inserted:20 4-INSERT 2- TRAVERSAL 3-QUIT Enter your choice:2 Inder Traversal 20:30 405060 70 8090, Preorder Traversal 50 30 2040 70.60 8090 Postotder Traversal 2040 3060 90 80 70.50 1-INSERT 2- TRAVERSAL 3-QUIT Enter your choice’3 OS PT pein ofa node d notanclementfom a single node trees trivial. Consider deleting an clement ave having more than one element. First, search for ein Tf not found, aes ible, Otherwise, suppose the node n contains. Deleting node mus ike that wit itt terete problems forthe binary tree 7. We find the inorder successor n (We could ith th inorder predecesscr). Since is alo a binary search ree, he element in vandal follows ¢, in the set of element stored in T when aranged in ascending we jfanon NULL 7, exist, then we can replace e in by the element in m,, We can then. et the nede n, from T If, however, a non NULL n, does not exist, n can simply be ns by aking the parent of pinto the et child of. This completes deletion ofe gon considered a inary search tee. ehavetonow maintain the AVL properly of 7 Suppose the deletion of anode ha eventually ken plaeat node x, which means the subtre rooted atx as reduced in height by one, We sow hae to check the balance factor ofthe parent, of x Asin insertion, we may have to dorebalancing at z. This may oF may not reduce the height ofthe subtree rooted at. Ifnot, the AVL deletion is complete. Fit has reduced, we have to again move up towards the root rode, Inthe worst case, We may have to finally look at the root node and the height of T wich may reduce by 1 Deletion procedure is more complex than insertion in two ways: ')- more numberof cases for rebalancing may arise in deletion; iin insertion there is only one rebalancing, but in deletion there can be as many rebalancingas the length of the path from the (eventually) deleted node tothe root. Time complexity of deletion Basically to perform deletion the total number of operations isin the worts case, proportional tothe height ofthe re, where each operation isa rebalancing operation, moving up one spor moving down one sep, and is bounded by constant time fr each such operation Therefore the time for deletion in the worst case is (A) = O(log), where, hs the height ofthe tee and mis the number of nodes inthe tee 6.16 # Data Structures Using C Example: — Delete 4,8,6,5,2. 1,7 iz Delete 4 41s a leaf node soitis deleted directly @Q H @ bo Rotate leftat3 gives ObS Trees 677 ee der predecessor of eet epee With 7 Q is GQ © OO Y® © ® Me 6s aleaf node, tis deleted directly Rolate right t7 gives Q Q "Pg Snoeinorder predecessor of 5is3.So, replace 5 with 3 Q 6 fia) OY 6.78 & Data Structures Using C Delete 2 1B) rom rat 08 — = Q Go 690 one S @ Reiter 9 ahe8 @) © Q > Oo > ‘since inorder predecessor of Fis 3. So, replace 7 with 3

You might also like