1 Copyright 2012 by Pearson Education, Inc. All Rights Reserved.

Size: px
Start display at page:

Download "1 Copyright 2012 by Pearson Education, Inc. All Rights Reserved."

Transcription

1 CHAPTER 20 AVL Trees Objectives To know wat an AVL tree is ( 20.1). To understand ow to rebalance a tree using te LL rotation, LR rotation, RR rotation, and RL rotation ( 20.2). To know ow to design te AVLTree class ( 20.3). To insert elements into an AVL tree ( 20.4). To implement node rebalancing ( 20.5). To delete elements from an AVL tree ( 20.6). To implement te AVLTree class ( 20.7). To test te AVLTree class ( 20.8). To analyze te complexity of searc, insert, and delete operations in AVL trees ( 20.9). 1

2 20.1 Introduction Key Point: AVL Tree is a balanced binary searc tree. Capter 19 introduced binary searc trees. Te searc, insertion, and deletion time for a binary tree depend on te eigt of te tree. In te worst case, te eigt is O (n). If a tree is perfectly balanced i.e., a complete binary tree its eigt is log n. Can we maintain a perfectly balanced tree? Yes. But doing so will be costly. Te compromise is to maintain a well-balanced tree i.e., te eigts of two subtrees for every node are about te same. AVL trees are well balanced. AVL trees were invented in 1962 by two Russian computer scientists G. M. Adelson-Velsky and E. M. Landis. In an AVL tree, te difference between te eigts of two subtrees for every node is 0 or 1. It can be sown tat te maximum eigt of an AVL tree is O (logn). Te process for inserting or deleting an element in an AVL tree is te same as in a regular binary searc tree. Te difference is tat you may ave to rebalance te tree after an insertion or deletion operation. Te balance factor of a node is te eigt of its rigt subtree minus te eigt of its left subtree. A node is said to be balanced if its balance factor is -1, 0, or 1. A node is said to be left-eavy if its balance factor is -1. A node is said to be rigt-eavy if its balance factor is +1. Pedagogical NOTE Run from l to see ow an AVL tree works, as sown in Figure

3 Figure 20.1 Te animation tool enables you to insert, delete, and searc elements visually Rebalancing Trees Key Point: After inserting or deleting an element from an AVL tree, if te tree becomes unbalanced, perform a rotation operation to rebalance te tree. If a node is not balanced after an insertion or deletion operation, you need to rebalance it. Te process of rebalancing a node is called a rotation. Tere are four possible rotations. LL Rotation: An LL imbalance occurs at a node A suc tat A as a balance factor -2 and a left cild B wit a balance factor -1 or 0, as sown in Figure 20.2a. Tis type of imbalance can be fixed by performing a single rigt rotation at A, as sown in Figure 20.2b. 3

4 A -2 0 or 1 B -1 or 0 B A 0 or -1 T3 +1 T1 +1 T1 T2 T2 T3 T2 s eigt is or +1 (a) (b) Figure 20.2 LL rotation fixes LL imbalance. RR Rotation: An RR imbalance occurs at a node A suc tat A as a balance factor +2 and a rigt cild B wit a balance factor +1 or 0, as sown in Figure 20.3a. Tis type of imbalance can be fixed by performing a single left rotation at A, as sown in Figure 20.3b. A +2 B 0 or -1 T3 B +1 or 0 0 or +1 A T1 +1 T2 s eigt is or +1 T2 T1 +1 T3 T2 (a) (b) Figure 20.3 RR rotation fixes RR imbalance. 4

5 LR Rotation: An LR imbalance occurs at a node A suc tat A as a balance factor -2 and a left cild B wit a balance factor +1, as sown in Figure 20.4a. Assume B s rigt cild is C. Tis type of imbalance can be fixed by performing a double rotation at A (first a single left rotation at B and ten a single rigt rotation at A), as sown in Figure 20.4b. A -2 C 0 +1 B 0 or -1 B A 0 or 1 T4 T1 C -1, 0, or 1 T1 T2 T3 T4 T2 T3 T2 and T3 may ave different eigt, but at least one must ave eigt of. (a) (b) Figure 20.4 LR rotation fixes LR imbalance. RL Rotation: An RL imbalance occurs at a node A suc tat A as a balance factor +2 and a rigt cild B wit a balance factor -1, as sown in Figure 20.5a. Assume B s left cild is C. Tis type of imbalance can be fixed by performing a double rotation at A (first a single rigt rotation at B and ten a single left rotation at A), as sown in Figure 20.5b. A +2 C 0 T1-1 B 0 or -1 A B 0 or 1 0, -1, or 1 C T4 T1 T2 T3 T4 T2 T3 T2 and T3 may ave different eigt, but at leas t one m ust ave eigt of. (a) (b) 5

6 Figure 20.5 RL rotation fixes RL imbalance. Ceck point 20.1 Wat is an AVL tree? Describe te following terms: balance factor, left-eavy, and rigt-eavy Sow te balance factor of eac node in te tree, as sown in Figure (a) (b) Figure 20.6 A balance factor determines weter a node is balanced Describe LL rotation, RR rotation, LR rotation, and RL rotation for an AVL tree For te AVL tree in Figure 20.6a, sow te new AVL tree after adding element 89. Wat rotation did you perform in order to rebalance te tree? Wic node was unbalanced? 20.5 For te AVL tree in Figure 20.6a, sow te new AVL tree after adding element 40. Wat rotation did you perform in order to rebalance te tree? Wic node was unbalanced? 6

7 20.6 For te AVL tree in Figure 20.6a, sow te new AVL tree after adding element 40. Wat rotation did you perform in order to rebalance te tree? Wic node was unbalanced? 20.7 For te AVL tree in Figure 20.6a, sow te new AVL tree after adding element 40. Wat rotation did you perform in order to rebalance te tree? Wic node was unbalanced? 20.8 For te AVL tree in Figure 20.6a, sow te new AVL tree after adding element 47. Wat rotation did you perform in order to rebalance te tree? Wic node was unbalanced? 20.9 For te AVL tree in Figure 20.6a, sow te new AVL tree after adding element 81. Wat rotation did you perform in order to rebalance te tree? Wic node was unbalanced? For te AVL tree in Figure 20.6b, sow te new AVL tree after adding element 200. Wat rotation did you perform in order to rebalance te tree? Wic node was unbalanced? 20.3 Designing Classes for AVL Trees Key Point: Since an AVL tree is a binary searc tree, AVLTree is designed as a subclass of BST. An AVL tree is a binary tree. So you can define te AVLTree class to extend te BST class, as sown in Figure Te BST and TreeNode classes are defined in An AVL tree is a binary tree. So, you can define te AVLTree class to extend te BST class, as sown in Figure Te BST and TreeNode classes are defined in

8 TreeNode BST AVLTreeNode m 0 AVLTree e igt: int Link 1 AVLTree() createnewnode(): AVLTreeNode insert(e: object): bool delete(e: object): bool updateheigt(node: AVLTreeNode): None balancepat(e: object): None balancefactor(node: AVLTreeNode): int balancell(a: TreeNode, parentofa: TreeNode): None balancelr(a: TreeNode, parentofa: TreeNode): None balancerr(a: TreeNode, parentofa: TreeNode): None balancerl(a: TreeNode, parentofa: TreeNode): None Creates an empty AVL tree. Override tis metod to create an AVLTreeNode. Returns true if te element is added successfully. Returns true if te element is removed from te tree successfully. Resets te eigt of te specified node. Balances te nodes in te pat from te node for t e elem ent t o te root i f needed. Returns te balance factor of te node. Performs LL balance. Performs LR balance. Performs RR balance. Performs RL balance. Figure 20.7 Te AVLTree class extends BST wit new implementations for te insert and delete metods. In order to balance te tree, you need to know eac node s eigt. For convenience, store te eigt of eac node in AVLTreeNode and define AVLTreeNode to be a subclass of BianryTree.TreeNode. Note tat TreeNode is defined as a static inner class in BST. AVLTreeNode will be defined as a static inner class. TreeNode contains te data fields element, left, and rigt, wic are inerited in AVLTreeNode. So, AVLTreeNode contains four data fields, as pictured in Figure node: AVLTreeNode element: E eigt: int left: TreeNode<E> rigt: TreeNode<E> Figure 20.8 An AVLTreeNode contains protected data fields element, eigt, left, and rigt. 8

9 In te BST class, te createnewnode() metod creates a TreeNode object. Tis metod is overridden in te AVLTree class to create an AVLTreeNode. Note tat te return type of te createnewnode() metod in te BianryTree class is TreeNode, but te return type of te createnewnode() metod in AVLTree class is AVLTreeNode. Tis is fine, since AVLTreeNode is a subtype of TreeNode. Searcing an element in an AVLTree is te same as searcing in a regular binary tree. So, te searc metod defined in te BST class also works for AVLTree. Te insert and delete metods are overridden to insert and delete an element and perform rebalancing operations if necessary to ensure tat te tree is balanced Overriding te insert Metod Key Point: Inserting an element into an AVL tree is te same as inserting it to a BST, except tat te tree may need to be rebalanced. A new element is always inserted as a leaf node. Te eigts of te ancestors of te new leaf node may increase, as a result of adding a new node. After insertion, ceck te nodes along te pat from te new leaf node up to te root. If a node is found unbalanced, perform an appropriate rotation using te following algoritm in Listing Listing 20.1 Balancing Nodes on a Pat balancepat(e): Get te pat from te node tat contains element e to te root, as illustrated in Figure 20.9 for eac node A in te pat leading to te root { Update te eigt of A Let parentofa denote te parent of A, wic is te next node in te pat, or None if A is te root if balancefactor(a) == -2: if balancefactor(a.left) == -1 or 0: Perform LL rotation # See Figure 20.2 else: Perform LR rotation # See Figure 20.4 else balancefactor(a) == +2: if balancefactor(a.rigt) == +1 or 0: 9

10 Perform RR rotation # See Figure 20.3 else: Perform RL rotation # See Figure 20.5 root A parentofa Figure 20.9 New node contains element o Te nodes along te pat from te new leaf node may become unbalanced. Te algoritm considers eac node in te pat from te new leaf node to te root. Update te eigt of te node on te pat. If a node is balanced, no action is needed. If a node is not balanced, perform an appropriate rotation Implementing Rotations Key Point: An unbalanced tree becomes balanced by performing an appropriate rotation operation. Section 20.2, Rebalancing Tree, illustrated ow to perform rotations at a node. Listing 20.2 gives te algoritm for te LL rotation, as pictured in Figure Listing 20.2 LL Rotation Algoritm balancell(a, parentofa): Let B be te left cild of A. if A is te root: Let B be te new root else: if A is a left cild of parentofa: Let B be a left cild of parentofa else: Let B be a rigt cild of parentofa 10

11 Make T2 te left subtree of A by assigning B.rigt to A.left Make A te left cild of B by assigning A to B.rigt Update te eigt of node A and node B Note tat te eigt of nodes A and B may be canged, but te eigts of oter nodes in te tree are not canged. Similarly, you can implement te RR rotation, LR rotation, and RL rotation Implementing te delete Metod Key Point: Deleting an element from an AVL tree is te same as deleing it from a BST, except tat te tree may need to be rebalanced. As discussed in Section 20.3, Deleting Elements in a BST, to delete an element from a binary tree, te algoritm first locates te node tat contains te element. Let current point to te node tat contains te element in te binary tree and parent point to te parent of te current node. Te current node may be a left cild or a rigt cild of te parent node. Tree cases arise wen deleting an element: Case 1: Te current node does not ave a left cild, as sown in Figure 20.10a. To delete te current node, simply connect te parent wit te rigt cild of te current node, as sown in Figure 20.10b. Te eigt of te nodes along te pat from te parent up to te root may ave decreased. To ensure te tree is balanced, invoke balancepat(parent.element) # Defined in Listing 20.1 Case 2: Te current node as a left cild. Let rigtmost point to te node tat contains te largest element in te left subtree of te current node and parentofrigtmost point to te parent node of te rigtmost node, as sown in Figure 20.12a. Te rigtmost node cannot ave a rigt cild but may ave a left cild. Replace te element value in te current node wit te one in te rigtmost node, connect te parentofrigtmost node wit te left cild of te rigtmost node, and delete te rigtmost node, as sown in Figure 20.12b. 11

12 Te eigt of te nodes along te pat from parentofrigtmost up to te root may ave decreased. To ensure tat te tree is balanced, invoke balancepat(parentofrigtmost) # Defined in Listing Te AVLTree Class Key Point: Te AVLTree class extends te BST class to override te insert and delete metods to rebalance te tree if necessary. Listing 20.3 gives te complete source code for te AVLTree class. Listing 20.3 AVLTree.py 1 from BST import BST 2 from BST import TreeNode 3 4 class AVLTree(BST): 5 def init (self): 6 BST. init (self) 7 8 # Override te createnewnode metod to create an AVLTreeNode 9 def createnewnode(self, e): 10 return AVLTreeNode(e) # Override te insert metod to balance te tree if necessary 13 def insert(self, o): 14 successful = BST.insert(self, o) 15 if not successful: 16 return False # o is already in te tree 17 else: 18 self.balancepat(o) # Balance from o to te root if necessary return True # o is inserted # Update te eigt of a specified node 23 def updateheigt(self, node): 24 if node.left == None and node.rigt == None: # node is a leaf 25 node.eigt = 0 26 elif node.left == None: # node as no left subtree 27 node.eigt = 1 + (node.rigt).eigt 28 elif node.rigt == None: # node as no rigt subtree 29 node.eigt = 1 + (node.left).eigt 30 else: 31 node.eigt = 1 + max((node.rigt).eigt, (node.left).eigt) # Balance te nodes in te pat from te specified 34 # node to te root if necessary 35 def balancepat(self, o): 36 pat = BST.pat(self, o); 37 for i in range(len(pat) - 1, -1, -1): 38 A = pat[i] 39 self.updateheigt(a) 40 parentofa = None if (A == self.root) else pat[i - 1] if self.balancefactor(a) == -2: 12

13 43 if self.balancefactor(a.left) <= 0: 44 self.balancell(a, parentofa) # Perform LL rotation 45 else: 46 self.balancelr(a, parentofa) # Perform LR rotation 47 elif self.balancefactor(a) == +2: 48 if self.balancefactor(a.rigt) >= 0: 49 self.balancerr(a, parentofa) # Perform RR rotation 50 else: 51 self.balancerl(a, parentofa) # Perform RL rotation # Return te balance factor of te node 54 def balancefactor(self, node): 55 if node.rigt == None: # node as no rigt subtree 56 return -node.eigt 57 elif node.left == None: # node as no left subtree 58 return +node.eigt 59 else: 60 return (node.rigt).eigt - (node.left).eigt # Balance LL (see Figure 14.2) 63 def balancell(self, A, parentofa): 64 B = A.left # A is left-eavy and B is left-eavy if A == self.root: 67 self.root = B 68 else: 69 if parentofa.left == A: 70 parentofa.left = B 71 else: 72 parentofa.rigt = B A.left = B.rigt # Make T2 te left subtree of A 75 B.rigt = A # Make A te left cild of B 76 self.updateheigt(a) 77 self.updateheigt(b) # Balance LR (see Figure 14.2(c)) 80 def balancelr(self, A, parentofa): 81 B = A.left # A is left-eavy 82 C = B.rigt # B is rigt-eavy if A == self.root: 85 self.root = C 86 else: 87 if parentofa.left == A: 88 parentofa.left = C 89 else: 90 parentofa.rigt = C A.left = C.rigt # Make T3 te left subtree of A 93 B.rigt = C.left # Make T2 te rigt subtree of B 94 C.left = B 95 C.rigt = A # Adjust eigts 98 self.updateheigt(a) 99 self.updateheigt(b) 100 self.updateheigt(c) # Balance RR (see Figure 14.2(b)) 103 def balancerr(self, A, parentofa): 104 B = A.rigt # A is rigt-eavy and B is rigt-eavy if A == self.root: 107 self.root = B 108 else: 13

14 109 if parentofa.left == A: 110 parentofa.left = B 111 else: 112 parentofa.rigt = B A.rigt = B.left # Make T2 te rigt subtree of A 115 B.left = A 116 self.updateheigt(a) 117 self.updateheigt(b) # Balance RL (see Figure 14.2(d)) 120 def balancerl(self, A, parentofa): 121 B = A.rigt # A is rigt-eavy 122 C = B.left # B is left-eavy if A == self.root: 125 self.root = C 126 else: 127 if parentofa.left == A: 128 parentofa.left = C 129 else: 130 parentofa.rigt = C A.rigt = C.left # Make T2 te rigt subtree of A 133 B.left = C.rigt # Make T3 te left subtree of B 134 C.left = A 135 C.rigt = B # Adjust eigts 138 self.updateheigt(a) 139 self.updateheigt(b) 140 self.updateheigt(c) # Delete an element from te binary tree. 143 # Return True if te element is deleted successfully 144 # Return False if te element is not in te tree 145 def delete(self, element): 146 if self.root == None: 147 return False # Element is not in te tree # Locate te node to be deleted and also locate its parent node 150 parent = None 151 current = self.root 152 wile current!= None: 153 if element < current.element: 154 parent = current 155 current = current.left 156 elif element > current.element: 157 parent = current 158 current = current.rigt 159 else: 160 break # Element is in te tree pointed by current if current == None: 163 return False # Element is not in te tree # Case 1: current as no left cildren (See Figure 23.6) 166 if current.left == None: 167 # Connect te parent wit te rigt cild of te current node 168 if parent == None: 169 root = current.rigt 170 else: 171 if element < parent.element: 172 parent.left = current.rigt 173 else: 174 parent.rigt = current.rigt 14

15 # Balance te tree if necessary 177 self.balancepat(parent.element) 178 else: 179 # Case 2: Te current node as a left cild 180 # Locate te rigtmost node in te left subtree of 181 # te current node and also its parent 182 parentofrigtmost = current 183 rigtmost = current.left wile rigtmost.rigt!= None: 186 parentofrigtmost = rigtmost 187 rigtmost = rigtmost.rigt # Keep going to te rigt # Replace te element in current by te element in rigtmost 190 current.element = rigtmost.element # Eliminate rigtmost node 193 if parentofrigtmost.rigt == rigtmost: 194 parentofrigtmost.rigt = rigtmost.left 195 else: 196 # Special case: parentofrigtmost is current 197 parentofrigtmost.left = rigtmost.left # Balance te tree if necessary 200 self.balancepat(parentofrigtmost.element) self.size -= 1 # One element deleted 203 return True # Element inserted # AVLTreeNode is TreeNode plus eigt 206 class AVLTreeNode(TreeNode): 207 def init (self, e): 208 self.eigt = 0 # New data field 209 TreeNode. init (self, e) Te AVLTree class extends BST (line 4). Its constructor invokes its superclass s constructor to initialize root and size property of a binary tree (line 6). Te createnewnode() metod defined in te BST class creates a TreeNode. Tis metod is overridden to return an AVLTreeNode (lines 9 10). Tis is a variation of te Factory Metod Pattern. Design Pattern: Factory Metod Pattern Te Factory Metod pattern defines an abstract metod for creating an object, but lets subclasses decide wic class to instantiate. Factory Metod lets a class defer instantiation to subclasses. Te insert metod in AVLTree is overridden in lines Te metod first invokes te insert metod in BST, ten invokes balancepat(o) (line 18) to ensure tat te tree is balanced. 15

16 Te balancepat metod first gets te nodes on te pat from te node tat contains element o to te root (line 36). For eac node in te pat, update its eigt (line 39), ceck its balance factor (line 42), and perform appropriate rotations if necessary (lines 42 51). Four metods for performing rotations are defined in lines Eac metod is invoked wit two TreeNode arguments A and parentofa to perform an appropriate rotation at node A. How eac rotation is performed is pictured in Figures After te rotation, te eigts of nodes A, B, and C are updated for te LL and RR rotations (lines 76, 98, 116, 138). Te delete metod in AVLTree is overridden in lines Te metod is te same as te one implemented in te BST class, except tat you ave to rebalance te nodes after deletion in two cases (lines 177, 200) Testing te AVLTree Class Key Point: Tis section gives an example of using te AVLTree class. Listing 20.4 gives a test program. Te program creates an AVLTree initialized wit an array of integers 25, 20, and 5 (lines 6 7), inserts elements in lines 11 20, and deletes elements in lines Listing 20.4 TestAVLTree.py from AVLTree import AVLTree def main(): tree = AVLTree() tree.insert(25) tree.insert(20) tree.insert(5) print("after inserting 25, 20, 5:") printtree(tree) tree.insert(34) tree.insert(50) print("after inserting 34, 50:") printtree(tree) 16

17 tree.insert(30) print("after inserting 30") printtree(tree) tree.insert(10) print("after inserting 10") printtree(tree) tree.delete(34) tree.delete(30) tree.delete(50) print("after removing 34, 30, 50:") printtree(tree) tree.delete(5) print("after removing 5:") printtree(tree) def printtree(tree): # Traverse tree print("inorder (sorted): ", end = "") tree.inorder() print("\npostorder: ", end = "") tree.postorder() print("\npreorder: ", end = "") tree.preorder() print("\nte number of nodes is " + str(tree.getsize())) print() main() # Call te main function Sample output After inserting 25, 20, 5: Inorder (sorted): Postorder: Preorder: Te number of nodes is 3 After inserting 34, 50: Inorder (sorted): Postorder: Preorder: Te number of nodes is 5 After inserting 30 Inorder (sorted): Postorder: Preorder: Te number of nodes is 6 After inserting 10 Inorder (sorted): Postorder: Preorder: Te number of nodes is 7 After removing 34, 30, 50: 17

18 Inorder (sorted): Postorder: Preorder: Te number of nodes is 4 After removing 5: Inorder (sorted): Postorder: Preorder: Te number of nodes is 3 Figure sows ow te tree evolves as elements are added to te tree. After 25 and 20 are added, te tree is as sown in Figure 20.10a. 5 is inserted as a left cild of 20, as sown in Figure 20.10b. Te tree is not balanced. It is left-eavy at node 25. Perform an LL rotation to result an AVL tree, as sown in Figure 20.10c. After inserting 34, te tree is sown in Figure 20.10d. After inserting 50, te tree is as sown in Figure 20.10e. Te tree is not balanced. It is rigt-eavy at node 25. Perform an RR rotation to result in an AVL tree, as sown in Figure 20.10f. After inserting 30, te tree is as sown in Figure 20.10g. Te tree is not balanced. Perform an LR rotation to result in an AVL tree, as sown in Figure After inserting 10, te tree is as sown in Figure 20.10i. Te tree is not balanced. Perform an RL rotation to result in an AVL tree, as sown in Figure 20.10j. 25 Need LL rotation at node (a) Insert 25, 20 (b) Insert 5 (c) Balacned (d) Insert 34 18

19 20 Need RR rotation at node RL rotation at node (e) Insert 50 (f) Balanced (g) Insert LR rotation at node () Balanced (i) Insert 10 (j) Balanced Figure Te tree evolves as new elements are inserted. Figure sows ow te tree evolves as elements are deleted. After deleting 34, 30, and 50, te tree is as sown in Figure 20.11b. Te tree is not balanced. Perform an LL rotation to result an AVL tree, as sown in Figure 20.11c. After deleting 5, te tree is as sown in Figure 20.11d. Te tree is not balanced. Perform an RL rotation to result in an AVL tree, as sown in Figure 20.11e. 19

20 LL rotation at node (a) Delete 34, 30, 50 (b) After 34, 30, 50 are deleted (c) Balanced RL rotation at (d) After 5 is deleted (e) Balanced Figure Te tree evolves as te elements are deleted from te tree Maximum Heigt of an AVL Tree Key Point: Since te eigt of an AVL tree is O(log n), te time complexity of te searc, insert, and delete metods in AVLTree is O(log n). Te time complexity of te searc, insert, and delete metods in AVLTree depends on te eigt of te tree. We can prove tat te eigt of te tree is O (logn). Let G () denote te minimum number of te nodes in an AVL tree wit eigt. Obviously, (1) and G (2) is 2. Te minimum number of nodes in an AVL tree wit eigt 3 minimum subtrees: one wit eigt 1 and te oter wit eigt 2 G ( ) G( 1) G( 2) 1 must ave two. So, G is 1 20

21 Recall tat a Fibonacci number at index i can be described using te recurrence relation F ( i) F( i 1) F( i 2). So, te function G () is essentially te same as F (i) tat log( n 2) were n is te number of nodes in te tree. Terefore, te eigt of an AVL tree is O (logn).. It can be proven Te searc, insert, and delete metods involve only te nodes along a pat in te tree. Te updateheigt and balancefactor metods are executed in a constant time for eac node in te pat. Te balancepat metod is executed in a constant time for a node in te pat. So, te time complexity for te searc, insert, and delete metods is O (logn). Ceck point Wy is te createnewnode metod protected? Wen is te updateheigt metod invoked? Wen is te balancefacotor metod invoked? Wen is te balanacepat metod invoked? Wat are te data fields in te AVLTreeNode class? Wat are data fields in te AVLTree class? In te insert and delete metods, once you ave performed a rotation to balance a node in te tree, is it possible tat tere are still unbalanced nodes? Sow te cange of an AVL tree wen inserting 1, 2, 3, 4, 10, 9, 7, 5, 8, 6 into te tree, in tis order For te tree built in te preceding question, sow its cange after 1, 2, 3, 4, 10, 9, 7, 5, 8, 6 are deleted from te tree in tis order. Key Terms 21

22 AVL tree LL rotation LR rotation RR rotation RL rotation balance factor left-eavy rigt-eavy rotation perfectly balanced well-balanced Capter Summary 1. An AVL tree is a well-balanced binary tree. In an AVL tree, te difference between te eigts of two subtrees for every node is 0 or Te process for inserting or deleting an element in an AVL tree is te same as in a regular binary searc tree. Te difference is tat you may ave to rebalance te tree after an insertion or deletion operation. 3. Imbalances in te tree caused by insertions and deletions are rebalanced troug subtree rotations at te node of te imbalance. 4. Te process of rebalancing a node is called a rotation. Tere are four possible rotations: LL rotation, LR rotation, RR rotation, and RL rotation. 5. Te eigt of an AVL tree is O (logn). So, te time complexities for te searc, insert, and delete metods are O (logn). Multiple-Coice Questions See multiple-coice questions online at liang.armstrong.edu/selftest/selftestpy?capter=20. 22

23 Programming Exercises *20.1 (Displaying AVL tree grapically) Write an applet tat displays an AVL tree along wit its balance factor for eac node (Comparing performance) Write a test program tat randomly generates numbers and inserts tem into a BST, resuffles te numbers and performs searc, and resuffles te numbers again before deleting tem from te tree. Write anoter test program tat does te same ting for an AVLTree. Compare te execution times of tese two programs. **20.3 (Parent reference for BST) Suppose tat te TreeNode class defined in BST contains a reference to te node s parent, as sown in Exercise Implement te AVLTree class to support tis cange. Write a test program tat adds numbers 1, 2,..., 100 to te tree and displays te pats for all leaf nodes. **20.4 (Te kt smallest element) You can find te kt smallest element in a BST in O (n) time from an inorder iterator. For an AVL tree, you can find it in O (log n) time. To acieve tis, add a new data field named size in AVLTreeNode to store te number of nodes in te subtree rooted at tis node. Note tat te size of a node v is one more tan te sum of te sizes of its two cildren. Figure sows an AVL tree and te size value for eac node in te tree. 25 size: 6 20 size: 2 34 size: 3 5 size: 1 30 size: 1 50 size: 1 23

24 Figure Te size data field in AVLTreeNode stores te number of nodes in te subtree rooted at te node. In te AVLTree class, add te following metod to return te kt smallest element in te tree. def find(k) Te metod returns None if k < 1 or k > te size of te tree. Tis metod can be implemented using a recursive metod find(k, root) tat returns te kt smallest element in te tree wit te specified root. Let A and B be te left and rigt cildren of te root, respectively. Assuming tat te tree is not empty and k root. size, find(k, root) can be recursively defined as follows: root.element, if A is null and k is 1; B.element, if A is null and k is 2; find( k, root) f( k, A), if k A.size; root.element, if k A.size 1; f( k- Asize. -1, B), if k A.size 1; Modify te insert and delete metods in AVLTree to set te correct value for te size property in eac node. Te insert and delete metods will still be in O (logn) time. Te find(k) metod can be implemented in O (logn) time. Terefore, you can find te kt smallest element in an AVL tree in O (log n) time. ***20.5 (AVL tree animation) Write a program tat animates te AVL tree insert, delete, and searc metods, as sown in Figure **20.6 (Closest pair of points) Section 23.8 introduced an algoritm for finding a closest pair of points in O ( n log n) time using a divide-and-conquer approac. Te algoritm was implemented 24

25 using recursion wit a lot of overead. Using te plain-sweep approac along wit an AVL tree, you can solve te same problem in O ( n log n) time. Implement te algoritm using an AVLTree. 25

AVL Trees. CSE260, Computer Science B: Honors Stony Brook University

AVL Trees. CSE260, Computer Science B: Honors Stony Brook University AVL Trees CSE260, Computer Science B: Honors Stony Brook University ttp://www.cs.stonybrook.edu/~cse260 1 Objectives To know wat an AVL tree is To understand ow to rebalance a tree using te LL rotation,

More information

each node in the tree, the difference in height of its two subtrees is at the most p. AVL tree is a BST that is height-balanced-1-tree.

each node in the tree, the difference in height of its two subtrees is at the most p. AVL tree is a BST that is height-balanced-1-tree. Data Structures CSC212 1 AVL Trees A binary tree is a eigt-balanced-p-tree if for eac node in te tree, te difference in eigt of its two subtrees is at te most p. AVL tree is a BST tat is eigt-balanced-tree.

More information

CE 221 Data Structures and Algorithms

CE 221 Data Structures and Algorithms CE Data Structures and Algoritms Capter 4: Trees (AVL Trees) Text: Read Weiss, 4.4 Izmir University of Economics AVL Trees An AVL (Adelson-Velskii and Landis) tree is a binary searc tree wit a balance

More information

Announcements. Lilian s office hours rescheduled: Fri 2-4pm HW2 out tomorrow, due Thursday, 7/7. CSE373: Data Structures & Algorithms

Announcements. Lilian s office hours rescheduled: Fri 2-4pm HW2 out tomorrow, due Thursday, 7/7. CSE373: Data Structures & Algorithms Announcements Lilian s office ours resceduled: Fri 2-4pm HW2 out tomorrow, due Tursday, 7/7 CSE373: Data Structures & Algoritms Deletion in BST 2 5 5 2 9 20 7 0 7 30 Wy migt deletion be arder tan insertion?

More information

AVL Trees Outline and Required Reading: AVL Trees ( 11.2) CSE 2011, Winter 2017 Instructor: N. Vlajic

AVL Trees Outline and Required Reading: AVL Trees ( 11.2) CSE 2011, Winter 2017 Instructor: N. Vlajic 1 AVL Trees Outline and Required Reading: AVL Trees ( 11.2) CSE 2011, Winter 2017 Instructor: N. Vlajic AVL Trees 2 Binary Searc Trees better tan linear dictionaries; owever, te worst case performance

More information

Binary Search Tree - Best Time. AVL Trees. Binary Search Tree - Worst Time. Balanced and unbalanced BST

Binary Search Tree - Best Time. AVL Trees. Binary Search Tree - Worst Time. Balanced and unbalanced BST AL Trees CSE Data Structures Unit Reading: Section 4.4 Binary Searc Tree - Best Time All BST operations are O(d), were d is tree dept minimum d is d = log for a binary tree N wit N nodes at is te best

More information

CS 234. Module 6. October 16, CS 234 Module 6 ADT Dictionary 1 / 33

CS 234. Module 6. October 16, CS 234 Module 6 ADT Dictionary 1 / 33 CS 234 Module 6 October 16, 2018 CS 234 Module 6 ADT Dictionary 1 / 33 Idea for an ADT Te ADT Dictionary stores pairs (key, element), were keys are distinct and elements can be any data. Notes: Tis is

More information

Wrap up Amortized Analysis; AVL Trees. Riley Porter Winter CSE373: Data Structures & Algorithms

Wrap up Amortized Analysis; AVL Trees. Riley Porter Winter CSE373: Data Structures & Algorithms CSE 373: Data Structures & Wrap up Amortized Analysis; AVL Trees Riley Porter Course Logistics Symposium offered by CSE department today HW2 released, Big- O, Heaps (lecture slides ave pseudocode tat will

More information

CSE 332: Data Structures & Parallelism Lecture 8: AVL Trees. Ruth Anderson Winter 2019

CSE 332: Data Structures & Parallelism Lecture 8: AVL Trees. Ruth Anderson Winter 2019 CSE 2: Data Structures & Parallelism Lecture 8: AVL Trees Rut Anderson Winter 29 Today Dictionaries AVL Trees /25/29 2 Te AVL Balance Condition: Left and rigt subtrees of every node ave eigts differing

More information

CS 234. Module 6. October 25, CS 234 Module 6 ADT Dictionary 1 / 22

CS 234. Module 6. October 25, CS 234 Module 6 ADT Dictionary 1 / 22 CS 234 Module 6 October 25, 2016 CS 234 Module 6 ADT Dictionary 1 / 22 Case study Problem: Find a way to store student records for a course, wit unique IDs for eac student, were records can be accessed,

More information

Data Structures and Programming Spring 2014, Midterm Exam.

Data Structures and Programming Spring 2014, Midterm Exam. Data Structures and Programming Spring 2014, Midterm Exam. 1. (10 pts) Order te following functions 2.2 n, log(n 10 ), 2 2012, 25n log(n), 1.1 n, 2n 5.5, 4 log(n), 2 10, n 1.02, 5n 5, 76n, 8n 5 + 5n 2

More information

Lecture 7. Binary Search Trees / AVL Trees

Lecture 7. Binary Search Trees / AVL Trees Lecture 7. Binary Searc Trees / AVL Trees T. H. Cormen, C. E. Leiserson and R. L. Rivest Introduction to Algoritms, 3rd Edition, MIT Press, 2009 Sungkyunkwan University Hyunseung Coo coo@skku.edu Copyrigt

More information

When a BST becomes badly unbalanced, the search behavior can degenerate to that of a sorted linked list, O(N).

When a BST becomes badly unbalanced, the search behavior can degenerate to that of a sorted linked list, O(N). Balanced Binary Trees Binary searc trees provide O(log N) searc times provided tat te nodes are distributed in a reasonably balanced manner. Unfortunately, tat is not always te case and performing a sequence

More information

Advanced Tree. Structures. AVL Tree. Outline. AVL Tree Recall, Binary Search Tree (BST) is a special case of. Splay Tree (Ch 13.2.

Advanced Tree. Structures. AVL Tree. Outline. AVL Tree Recall, Binary Search Tree (BST) is a special case of. Splay Tree (Ch 13.2. ttp://1...0/csd/ Data tructure Capter 1 Advanced Tree tructures Dr. atrick Can cool of Computer cience and Engineering out Cina Universit of Tecnolog AVL Tree Recall, Binar earc Tree (BT) is a special

More information

TREES. General Binary Trees The Search Tree ADT Binary Search Trees AVL Trees Threaded trees Splay Trees B-Trees. UNIT -II

TREES. General Binary Trees The Search Tree ADT Binary Search Trees AVL Trees Threaded trees Splay Trees B-Trees. UNIT -II UNIT -II TREES General Binary Trees Te Searc Tree DT Binary Searc Trees VL Trees Treaded trees Splay Trees B-Trees. 2MRKS Q& 1. Define Tree tree is a data structure, wic represents ierarcical relationsip

More information

15-122: Principles of Imperative Computation, Summer 2011 Assignment 6: Trees and Secret Codes

15-122: Principles of Imperative Computation, Summer 2011 Assignment 6: Trees and Secret Codes 15-122: Principles of Imperative Computation, Summer 2011 Assignment 6: Trees and Secret Codes William Lovas (wlovas@cs) Karl Naden Out: Tuesday, Friday, June 10, 2011 Due: Monday, June 13, 2011 (Written

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 21, 2018 Outline Outline 1 C++ Supplement 1.3: Balanced Binary Search Trees Balanced Binary Search Trees Outline

More information

Design Patterns for Data Structures. Chapter 10. Balanced Trees

Design Patterns for Data Structures. Chapter 10. Balanced Trees Capter 10 Balanced Trees Capter 10 Four eigt-balanced trees: Red-Black binary tree Faster tan AVL for insertion and removal Adelsen-Velskii Landis (AVL) binary tree Faster tan red-black for lookup B-tree

More information

Design Patterns for Data Structures. Chapter 10. Balanced Trees

Design Patterns for Data Structures. Chapter 10. Balanced Trees Capter 10 Balanced Trees Capter 10 Four eigt-balanced trees: Red-Black binary tree Faster tan AVL for insertion and removal Adelsen-Velskii Landis (AVL) binary tree Faster tan red-black for lookup B-tree

More information

2 The Derivative. 2.0 Introduction to Derivatives. Slopes of Tangent Lines: Graphically

2 The Derivative. 2.0 Introduction to Derivatives. Slopes of Tangent Lines: Graphically 2 Te Derivative Te two previous capters ave laid te foundation for te study of calculus. Tey provided a review of some material you will need and started to empasize te various ways we will view and use

More information

Algorithms. AVL Tree

Algorithms. AVL Tree Algorithms AVL Tree Balanced binary tree The disadvantage of a binary search tree is that its height can be as large as N-1 This means that the time needed to perform insertion and deletion and many other

More information

CSI33 Data Structures

CSI33 Data Structures Department of Mathematics and Computer Science Bronx Community College Section 13.3: Outline 1 Section 13.3: Section 13.3: Improving The Worst-Case Performance for BSTs The Worst Case Scenario In the worst

More information

4.1 Tangent Lines. y 2 y 1 = y 2 y 1

4.1 Tangent Lines. y 2 y 1 = y 2 y 1 41 Tangent Lines Introduction Recall tat te slope of a line tells us ow fast te line rises or falls Given distinct points (x 1, y 1 ) and (x 2, y 2 ), te slope of te line troug tese two points is cange

More information

Section 2.3: Calculating Limits using the Limit Laws

Section 2.3: Calculating Limits using the Limit Laws Section 2.3: Calculating Limits using te Limit Laws In previous sections, we used graps and numerics to approimate te value of a it if it eists. Te problem wit tis owever is tat it does not always give

More information

MATH 5a Spring 2018 READING ASSIGNMENTS FOR CHAPTER 2

MATH 5a Spring 2018 READING ASSIGNMENTS FOR CHAPTER 2 MATH 5a Spring 2018 READING ASSIGNMENTS FOR CHAPTER 2 Note: Tere will be a very sort online reading quiz (WebWork) on eac reading assignment due one our before class on its due date. Due dates can be found

More information

4.2 The Derivative. f(x + h) f(x) lim

4.2 The Derivative. f(x + h) f(x) lim 4.2 Te Derivative Introduction In te previous section, it was sown tat if a function f as a nonvertical tangent line at a point (x, f(x)), ten its slope is given by te it f(x + ) f(x). (*) Tis is potentially

More information

Bounding Tree Cover Number and Positive Semidefinite Zero Forcing Number

Bounding Tree Cover Number and Positive Semidefinite Zero Forcing Number Bounding Tree Cover Number and Positive Semidefinite Zero Forcing Number Sofia Burille Mentor: Micael Natanson September 15, 2014 Abstract Given a grap, G, wit a set of vertices, v, and edges, various

More information

Part 2: Balanced Trees

Part 2: Balanced Trees Part 2: Balanced Trees 1 AVL Trees We could dene a perfectly balanced binary search tree with N nodes to be a complete binary search tree, one in which every level except the last is completely full. A

More information

Balanced Search Trees. CS 3110 Fall 2010

Balanced Search Trees. CS 3110 Fall 2010 Balanced Search Trees CS 3110 Fall 2010 Some Search Structures Sorted Arrays Advantages Search in O(log n) time (binary search) Disadvantages Need to know size in advance Insertion, deletion O(n) need

More information

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs Computational Optimization ISE 407 Lecture 16 Dr. Ted Ralphs ISE 407 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms in

More information

CS Transform-and-Conquer

CS Transform-and-Conquer CS483-11 Transform-and-Conquer Instructor: Fei Li Room 443 ST II Office hours: Tue. & Thur. 1:30pm - 2:30pm or by appointments lifei@cs.gmu.edu with subject: CS483 http://www.cs.gmu.edu/ lifei/teaching/cs483_fall07/

More information

2.8 The derivative as a function

2.8 The derivative as a function CHAPTER 2. LIMITS 56 2.8 Te derivative as a function Definition. Te derivative of f(x) istefunction f (x) defined as follows f f(x + ) f(x) (x). 0 Note: tis differs from te definition in section 2.7 in

More information

Balanced Binary Search Trees

Balanced Binary Search Trees Balanced Binary Search Trees In the previous section we looked at building a binary search tree. As we learned, the performance of the binary search tree can degrade to O(n) for operations like getand

More information

More Binary Search Trees AVL Trees. CS300 Data Structures (Fall 2013)

More Binary Search Trees AVL Trees. CS300 Data Structures (Fall 2013) More Binary Search Trees AVL Trees bstdelete if (key not found) return else if (either subtree is empty) { delete the node replacing the parents link with the ptr to the nonempty subtree or NULL if both

More information

19.2 Surface Area of Prisms and Cylinders

19.2 Surface Area of Prisms and Cylinders Name Class Date 19 Surface Area of Prisms and Cylinders Essential Question: How can you find te surface area of a prism or cylinder? Resource Locker Explore Developing a Surface Area Formula Surface area

More information

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree 0/2/ Preview Binary Tree Tree Binary Tree Property functions In-order walk Pre-order walk Post-order walk Search Tree Insert an element to the Tree Delete an element form the Tree A binary tree is a tree

More information

Announcements SORTING. Prelim 1. Announcements. A3 Comments 9/26/17. This semester s event is on Saturday, November 4 Apply to be a teacher!

Announcements SORTING. Prelim 1. Announcements. A3 Comments 9/26/17. This semester s event is on Saturday, November 4 Apply to be a teacher! Announcements 2 "Organizing is wat you do efore you do someting, so tat wen you do it, it is not all mixed up." ~ A. A. Milne SORTING Lecture 11 CS2110 Fall 2017 is a program wit a teac anyting, learn

More information

1.4 RATIONAL EXPRESSIONS

1.4 RATIONAL EXPRESSIONS 6 CHAPTER Fundamentals.4 RATIONAL EXPRESSIONS Te Domain of an Algebraic Epression Simplifying Rational Epressions Multiplying and Dividing Rational Epressions Adding and Subtracting Rational Epressions

More information

More BSTs & AVL Trees bstdelete

More BSTs & AVL Trees bstdelete More BSTs & AVL Trees bstdelete if (key not found) return else if (either subtree is empty) { delete the node replacing the parents link with the ptr to the nonempty subtree or NULL if both subtrees are

More information

CMPE 160: Introduction to Object Oriented Programming

CMPE 160: Introduction to Object Oriented Programming CMPE 6: Introduction to Object Oriented Programming General Tree Concepts Binary Trees Trees Definitions Representation Binary trees Traversals Expression trees These are the slides of the textbook by

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2016 Outline Outline 1 Chapter 7: Trees Outline Chapter 7: Trees 1 Chapter 7: Trees The Binary Search Property

More information

Trees. (Trees) Data Structures and Programming Spring / 28

Trees. (Trees) Data Structures and Programming Spring / 28 Trees (Trees) Data Structures and Programming Spring 2018 1 / 28 Trees A tree is a collection of nodes, which can be empty (recursive definition) If not empty, a tree consists of a distinguished node r

More information

More on Functions and Their Graphs

More on Functions and Their Graphs More on Functions and Teir Graps Difference Quotient ( + ) ( ) f a f a is known as te difference quotient and is used exclusively wit functions. Te objective to keep in mind is to factor te appearing in

More information

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap DATA STRUCTURES AND ALGORITHMS Hierarchical data structures: AVL tree, Bayer tree, Heap Summary of the previous lecture TREE is hierarchical (non linear) data structure Binary trees Definitions Full tree,

More information

BRONX COMMUNITY COLLEGE of the City University of New York DEPARTMENT OF MATHEMATICS AND COMPUTER SCIENCE

BRONX COMMUNITY COLLEGE of the City University of New York DEPARTMENT OF MATHEMATICS AND COMPUTER SCIENCE BRONX COMMUNITY COLLEGE of the City University of New York DEPARTMENT OF MATHEMATICS AND COMPUTER SCIENCE CSI Section E01 AVL Trees AVL Property While BST structures have average performance of Θ(log(n))

More information

Outline. An Application: A Binary Search Tree. 1 Chapter 7: Trees. favicon. CSI33 Data Structures

Outline. An Application: A Binary Search Tree. 1 Chapter 7: Trees. favicon. CSI33 Data Structures Outline Chapter 7: Trees 1 Chapter 7: Trees Approaching BST Making a decision We discussed the trade-offs between linked and array-based implementations of sequences (back in Section 4.7). Linked lists

More information

CSCE476/876 Spring Homework 5

CSCE476/876 Spring Homework 5 CSCE476/876 Spring 2016 Assigned on: Friday, Marc 11, 2016 Due: Monday, Marc 28, 2016 Homework 5 Programming assignment sould be submitted wit andin Te report can eiter be submitted wit andin as a PDF,

More information

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs Algorithms in Systems Engineering ISE 172 Lecture 16 Dr. Ted Ralphs ISE 172 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms

More information

n 1 i = n + i = n + f(n 1)

n 1 i = n + i = n + f(n 1) 2 Binary Search Trees Lab Objective: A tree is a linked list where each node in the list may refer to more than one other node. This structural flexibility makes trees more useful and efficient than regular

More information

Chapter 20: Binary Trees

Chapter 20: Binary Trees Chapter 20: Binary Trees 20.1 Definition and Application of Binary Trees Definition and Application of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two other

More information

, 1 1, A complex fraction is a quotient of rational expressions (including their sums) that result

, 1 1, A complex fraction is a quotient of rational expressions (including their sums) that result RT. Complex Fractions Wen working wit algebraic expressions, sometimes we come across needing to simplify expressions like tese: xx 9 xx +, xx + xx + xx, yy xx + xx + +, aa Simplifying Complex Fractions

More information

1 Copyright 2012 by Pearson Education, Inc. All Rights Reserved.

1 Copyright 2012 by Pearson Education, Inc. All Rights Reserved. CHAPTER 19 Binary Search Trees Objectives To design and implement a binary search tree ( 19.2). To represent binary trees using linked data structures ( 19.2.1). To search an element in a binary search

More information

Numerical Derivatives

Numerical Derivatives Lab 15 Numerical Derivatives Lab Objective: Understand and implement finite difference approximations of te derivative in single and multiple dimensions. Evaluate te accuracy of tese approximations. Ten

More information

CSCI2100B Data Structures Trees

CSCI2100B Data Structures Trees CSCI2100B Data Structures Trees Irwin King king@cse.cuhk.edu.hk http://www.cse.cuhk.edu.hk/~king Department of Computer Science & Engineering The Chinese University of Hong Kong Introduction General Tree

More information

CISC 235: Topic 4. Balanced Binary Search Trees

CISC 235: Topic 4. Balanced Binary Search Trees CISC 235: Topic 4 Balanced Binary Search Trees Outline Rationale and definitions Rotations AVL Trees, Red-Black, and AA-Trees Algorithms for searching, insertion, and deletion Analysis of complexity CISC

More information

Binary search trees (chapters )

Binary search trees (chapters ) Binary search trees (chapters 18.1 18.3) Binary search trees In a binary search tree (BST), every node is greater than all its left descendants, and less than all its right descendants (recall that this

More information

SORTING 9/26/18. Prelim 1. Prelim 1. Why Sorting? InsertionSort. Some Sorting Algorithms. Tonight!!!! Two Sessions:

SORTING 9/26/18. Prelim 1. Prelim 1. Why Sorting? InsertionSort. Some Sorting Algorithms. Tonight!!!! Two Sessions: Prelim 1 2 "Organizing is wat you do efore you do someting, so tat wen you do it, it is not all mixed up." ~ A. A. Milne SORTING Tonigt!!!! Two Sessions: You sould now y now wat room to tae te final. Jenna

More information

Analysis of Algorithms

Analysis of Algorithms Analysis of Algorithms Trees-I Prof. Muhammad Saeed Tree Representation.. Analysis Of Algorithms 2 .. Tree Representation Analysis Of Algorithms 3 Nomenclature Nodes (13) Size (13) Degree of a node Depth

More information

12.2 TECHNIQUES FOR EVALUATING LIMITS

12.2 TECHNIQUES FOR EVALUATING LIMITS Section Tecniques for Evaluating Limits 86 TECHNIQUES FOR EVALUATING LIMITS Wat ou sould learn Use te dividing out tecnique to evaluate its of functions Use te rationalizing tecnique to evaluate its of

More information

12.2 Techniques for Evaluating Limits

12.2 Techniques for Evaluating Limits 335_qd /4/5 :5 PM Page 863 Section Tecniques for Evaluating Limits 863 Tecniques for Evaluating Limits Wat ou sould learn Use te dividing out tecnique to evaluate its of functions Use te rationalizing

More information

Some Search Structures. Balanced Search Trees. Binary Search Trees. A Binary Search Tree. Review Binary Search Trees

Some Search Structures. Balanced Search Trees. Binary Search Trees. A Binary Search Tree. Review Binary Search Trees Some Search Structures Balanced Search Trees Lecture 8 CS Fall Sorted Arrays Advantages Search in O(log n) time (binary search) Disadvantages Need to know size in advance Insertion, deletion O(n) need

More information

Trees. A tree is a directed graph with the property

Trees. A tree is a directed graph with the property 2: Trees Trees A tree is a directed graph with the property There is one node (the root) from which all other nodes can be reached by exactly one path. Seen lots of examples. Parse Trees Decision Trees

More information

3.6 Directional Derivatives and the Gradient Vector

3.6 Directional Derivatives and the Gradient Vector 288 CHAPTER 3. FUNCTIONS OF SEVERAL VARIABLES 3.6 Directional Derivatives and te Gradient Vector 3.6.1 Functions of two Variables Directional Derivatives Let us first quickly review, one more time, te

More information

Binary search trees. We can define a node in a search tree using a Python class definition as follows: class SearchTree:

Binary search trees. We can define a node in a search tree using a Python class definition as follows: class SearchTree: Binary search trees An important use of binary trees is to store values that we may want to look up later. For instance, a binary search tree could be used to store a dictionary of words. A binary search

More information

Areas of Triangles and Parallelograms. Bases of a parallelogram. Height of a parallelogram THEOREM 11.3: AREA OF A TRIANGLE. a and its corresponding.

Areas of Triangles and Parallelograms. Bases of a parallelogram. Height of a parallelogram THEOREM 11.3: AREA OF A TRIANGLE. a and its corresponding. 11.1 Areas of Triangles and Parallelograms Goal p Find areas of triangles and parallelograms. Your Notes VOCABULARY Bases of a parallelogram Heigt of a parallelogram POSTULATE 4: AREA OF A SQUARE POSTULATE

More information

Balanced BST. Balanced BSTs guarantee O(logN) performance at all times

Balanced BST. Balanced BSTs guarantee O(logN) performance at all times Balanced BST Balanced BSTs guarantee O(logN) performance at all times the height or left and right sub-trees are about the same simple BST are O(N) in the worst case Categories of BSTs AVL, SPLAY trees:

More information

Materials: Whiteboard, TI-Nspire classroom set, quadratic tangents program, and a computer projector.

Materials: Whiteboard, TI-Nspire classroom set, quadratic tangents program, and a computer projector. Adam Clinc Lesson: Deriving te Derivative Grade Level: 12 t grade, Calculus I class Materials: Witeboard, TI-Nspire classroom set, quadratic tangents program, and a computer projector. Goals/Objectives:

More information

Trees. Reading: Weiss, Chapter 4. Cpt S 223, Fall 2007 Copyright: Washington State University

Trees. Reading: Weiss, Chapter 4. Cpt S 223, Fall 2007 Copyright: Washington State University Trees Reading: Weiss, Chapter 4 1 Generic Rooted Trees 2 Terms Node, Edge Internal node Root Leaf Child Sibling Descendant Ancestor 3 Tree Representations n-ary trees Each internal node can have at most

More information

Binary Trees, Binary Search Trees

Binary Trees, Binary Search Trees Binary Trees, Binary Search Trees Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search, insert, delete)

More information

Binary search trees (chapters )

Binary search trees (chapters ) Binary search trees (chapters 18.1 18.3) Binary search trees In a binary search tree (BST), every node is greater than all its left descendants, and less than all its right descendants (recall that this

More information

Hash-Based Indexes. Chapter 11. Comp 521 Files and Databases Spring

Hash-Based Indexes. Chapter 11. Comp 521 Files and Databases Spring Has-Based Indexes Capter 11 Comp 521 Files and Databases Spring 2010 1 Introduction As for any index, 3 alternatives for data entries k*: Data record wit key value k

More information

Week 2. TA Lab Consulting - See schedule (cs400 home pages) Peer Mentoring available - Friday 8am-12pm, 12:15-1:30pm in 1289CS

Week 2. TA Lab Consulting - See schedule (cs400 home pages) Peer Mentoring available - Friday 8am-12pm, 12:15-1:30pm in 1289CS ASSIGNMENTS h0 available and due before 10pm on Monday 1/28 h1 available and due before 10pm on Monday 2/4 p1 available and due before 10pm on Thursday 2/7 Week 2 TA Lab Consulting - See schedule (cs400

More information

Search Structures. Kyungran Kang

Search Structures. Kyungran Kang Search Structures Kyungran Kang (korykang@ajou.ac.kr) Ellis Horowitz, Sartaj Sahni and Susan Anderson-Freed, Fundamentals of Data Structures in C, 2nd Edition, Silicon Press, 2007. Contents Binary Search

More information

You Try: A. Dilate the following figure using a scale factor of 2 with center of dilation at the origin.

You Try: A. Dilate the following figure using a scale factor of 2 with center of dilation at the origin. 1 G.SRT.1-Some Tings To Know Dilations affect te size of te pre-image. Te pre-image will enlarge or reduce by te ratio given by te scale factor. A dilation wit a scale factor of 1> x >1enlarges it. A dilation

More information

CHAPTER 7: TRANSCENDENTAL FUNCTIONS

CHAPTER 7: TRANSCENDENTAL FUNCTIONS 7.0 Introduction and One to one Functions Contemporary Calculus 1 CHAPTER 7: TRANSCENDENTAL FUNCTIONS Introduction In te previous capters we saw ow to calculate and use te derivatives and integrals of

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms Spring 2009-2010 Outline BST Trees (contd.) 1 BST Trees (contd.) Outline BST Trees (contd.) 1 BST Trees (contd.) The bad news about BSTs... Problem with BSTs is that there

More information

Binary Search Tree. Revised based on textbook author s notes.

Binary Search Tree. Revised based on textbook author s notes. Binary Search Tree Revised based on textbook author s notes. Search Trees The tree structure can be used for searching. Each node contains a search key as part of its data or payload. Nodes are organized

More information

CS350: Data Structures AVL Trees

CS350: Data Structures AVL Trees S35: Data Structures VL Trees James Moscola Department of Engineering & omputer Science York ollege of Pennsylvania S35: Data Structures James Moscola Balanced Search Trees Binary search trees are not

More information

Section 1.2 The Slope of a Tangent

Section 1.2 The Slope of a Tangent Section 1.2 Te Slope of a Tangent You are familiar wit te concept of a tangent to a curve. Wat geometric interpretation can be given to a tangent to te grap of a function at a point? A tangent is te straigt

More information

AVL Trees / Slide 2. AVL Trees / Slide 4. Let N h be the minimum number of nodes in an AVL tree of height h. AVL Trees / Slide 6

AVL Trees / Slide 2. AVL Trees / Slide 4. Let N h be the minimum number of nodes in an AVL tree of height h. AVL Trees / Slide 6 COMP11 Spring 008 AVL Trees / Slide Balanced Binary Search Tree AVL-Trees Worst case height of binary search tree: N-1 Insertion, deletion can be O(N) in the worst case We want a binary search tree with

More information

COMP : Trees. COMP20012 Trees 219

COMP : Trees. COMP20012 Trees 219 COMP20012 3: Trees COMP20012 Trees 219 Trees Seen lots of examples. Parse Trees Decision Trees Search Trees Family Trees Hierarchical Structures Management Directories COMP20012 Trees 220 Trees have natural

More information

Data Structure - Advanced Topics in Tree -

Data Structure - Advanced Topics in Tree - Data Structure - Advanced Topics in Tree - AVL, Red-Black, B-tree Hanyang University Jong-Il Park AVL TREE Division of Computer Science and Engineering, Hanyang University Balanced binary trees Non-random

More information

COSC160: Data Structures Balanced Trees. Jeremy Bolton, PhD Assistant Teaching Professor

COSC160: Data Structures Balanced Trees. Jeremy Bolton, PhD Assistant Teaching Professor COSC160: Data Structures Balanced Trees Jeremy Bolton, PhD Assistant Teaching Professor Outline I. Balanced Trees I. AVL Trees I. Balance Constraint II. Examples III. Searching IV. Insertions V. Removals

More information

Motivation Computer Information Systems Storage Retrieval Updates. Binary Search Trees. OrderedStructures. Binary Search Tree

Motivation Computer Information Systems Storage Retrieval Updates. Binary Search Trees. OrderedStructures. Binary Search Tree Binary Search Trees CMPUT 115 - Lecture Department of Computing Science University of Alberta Revised 21-Mar-05 In this lecture we study an important data structure: Binary Search Tree (BST) Motivation

More information

Lecture 13: AVL Trees and Binary Heaps

Lecture 13: AVL Trees and Binary Heaps Data Structures Brett Bernstein Lecture 13: AVL Trees and Binary Heaps Review Exercises 1. ( ) Interview question: Given an array show how to shue it randomly so that any possible reordering is equally

More information

Fault Localization Using Tarantula

Fault Localization Using Tarantula Class 20 Fault localization (cont d) Test-data generation Exam review: Nov 3, after class to :30 Responsible for all material up troug Nov 3 (troug test-data generation) Send questions beforeand so all

More information

DATA STRUCTURES AND ALGORITHMS

DATA STRUCTURES AND ALGORITHMS LECTURE 13 Babeş - Bolyai University Computer Science and Mathematics Faculty 2017-2018 In Lecture 12... Binary Search Trees Binary Tree Traversals Huffman coding Binary Search Tree Today Binary Search

More information

Binary Trees. BSTs. For example: Jargon: Data Structures & Algorithms. root node. level: internal node. edge.

Binary Trees. BSTs. For example: Jargon: Data Structures & Algorithms. root node. level: internal node. edge. Binary Trees 1 A binary tree is either empty, or it consists of a node called the root together with two binary trees called the left subtree and the right subtree of the root, which are disjoint from

More information

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge Trees & Heaps Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Fall 2018 Jill Seaman!1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every

More information

CS211 Spring 2004 Lecture 06 Loops and their invariants. Software engineering reason for using loop invariants

CS211 Spring 2004 Lecture 06 Loops and their invariants. Software engineering reason for using loop invariants CS211 Spring 2004 Lecture 06 Loops and teir invariants Reading material: Tese notes. Weiss: Noting on invariants. ProgramLive: Capter 7 and 8 O! Tou ast damnale iteration and art, indeed, ale to corrupt

More information

AVL Trees. See Section 19.4of the text, p

AVL Trees. See Section 19.4of the text, p AVL Trees See Section 19.4of the text, p. 706-714. AVL trees are self-balancing Binary Search Trees. When you either insert or remove a node the tree adjusts its structure so that the remains a logarithm

More information

MAC-CPTM Situations Project

MAC-CPTM Situations Project raft o not use witout permission -P ituations Project ituation 20: rea of Plane Figures Prompt teacer in a geometry class introduces formulas for te areas of parallelograms, trapezoids, and romi. e removes

More information

Lecture 16: Binary Search Trees

Lecture 16: Binary Search Trees Extended Introduction to Computer Science CS1001.py Lecture 16: Binary Search Trees Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants: Michal Kleinbort, Amir Gilad School of Computer Science

More information

COMP171. AVL-Trees (Part 1)

COMP171. AVL-Trees (Part 1) COMP11 AVL-Trees (Part 1) AVL Trees / Slide 2 Data, a set of elements Data structure, a structured set of elements, linear, tree, graph, Linear: a sequence of elements, array, linked lists Tree: nested

More information

Lecture 16 Notes AVL Trees

Lecture 16 Notes AVL Trees Lecture 16 Notes AVL Trees 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning 1 Introduction Binary search trees are an excellent data structure to implement associative arrays,

More information

AVL Trees Goodrich, Tamassia, Goldwasser AVL Trees 1

AVL Trees Goodrich, Tamassia, Goldwasser AVL Trees 1 AVL Trees v 6 3 8 z 20 Goodrich, Tamassia, Goldwasser AVL Trees AVL Tree Definition Adelson-Velsky and Landis binary search tree balanced each internal node v the heights of the children of v can 2 3 7

More information

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology Introduction Chapter 4 Trees for large input, even linear access time may be prohibitive we need data structures that exhibit average running times closer to O(log N) binary search tree 2 Terminology recursive

More information

When the dimensions of a solid increase by a factor of k, how does the surface area change? How does the volume change?

When the dimensions of a solid increase by a factor of k, how does the surface area change? How does the volume change? 8.4 Surface Areas and Volumes of Similar Solids Wen te dimensions of a solid increase by a factor of k, ow does te surface area cange? How does te volume cange? 1 ACTIVITY: Comparing Surface Areas and

More information

Hash-Based Indexes. Chapter 11. Comp 521 Files and Databases Fall

Hash-Based Indexes. Chapter 11. Comp 521 Files and Databases Fall Has-Based Indexes Capter 11 Comp 521 Files and Databases Fall 2012 1 Introduction Hasing maps a searc key directly to te pid of te containing page/page-overflow cain Doesn t require intermediate page fetces

More information

Classify solids. Find volumes of prisms and cylinders.

Classify solids. Find volumes of prisms and cylinders. 11.4 Volumes of Prisms and Cylinders Essential Question How can you find te volume of a prism or cylinder tat is not a rigt prism or rigt cylinder? Recall tat te volume V of a rigt prism or a rigt cylinder

More information