logo
  • Writing Services
    • Writing Services
      • Essays & Papers
      • Essay Service
      • Write my research paper
      • Apa paper writing service
      • Dissertation writing services
      • Coursework writing service
      • Homework & Assignment
      • Pay for homework
      • English assignment help
      • Do my assignment
      • Assignment help
      • Finance assignment help
      • Do my math homework
      • Spss assignment help
      • Do my homework
      • Biology assignment help
      • Chemistry assignment help
      • More services
      • Personal statement writing service
      • Do my excel assignment
      • Law essay writing service
      • Annotated bibliography writing service
      • Nursing assignment help
      • Write my lab report
      • Capstone project writing service
      • Do my powerpoint presentation
  • Study Resources
    • Study Resources
      • Universities
      • Courses
      • Documents

Lecture Note

6.006 Introduction to Algorithms, Recitation 7

  • University:

    Massachusetts Institute of Technology
  • Course:

    6.006 | Introduction to Algorithms
  • Academic year:

    2020

  • Views:

    245

    Pages:

    10

  • Author:

    Reagan Tran

  • Last update:

    02.10.2024

Introduction to Algorithms: 6.006 Massachusetts Institute of Technology Instructors: Erik Demaine, Jason Ku, and Justin Solomon Recitation 7 Recitation 7 Balanced Binary Trees Previously, we discussed binary trees as a general data structure for storing items, without bounding the maximum height of the tree. The ultimate goal will be to keep our tree balanced: a tree on n nodes is balanced if its height is O(log n). Then all the O(h)-time operations we talked about last time will only take O(log n) time. There are many ways to keep a binary tree balanced under insertions and deletions (Red-Black Trees, B-Trees, 2-3 Trees, Splay Trees, etc.). The oldest (and perhaps simplest) method is called an AVL Tree. Every node of an AVL Tree is height-balanced (i.e., satisfies the AVL Property) where the left and right subtrees of a height-balanced node differ in height by at most 1. To put it a different way, define the skew of a node to be the height of its right subtree minus the height of its left subtree (where the height of an empty subtree is −1. Then a node is height-balanced if it’s skew is either −1, 0, or 1. A tree is height-balanced if every node in the tree is height-balanced. Height-balance is good because it implies balance! Exercise: A height-balanced tree is balanced. Solution: Balanced means that h = O(log n). Equivalently, balanced means that log n is lower bounded by Ω(h) so that n = 2Ω(h) . So if we can show the minimum number of nodes in a heightbalanced tree is at least exponential in h, then it must also be balanced. Let F (h) denote the fewest nodes in any height-balanced tree of height h. Then F (h) satisfies the recurrence: F (h) = 1 + F (h − 1) + F (h − 2) ≥ 2F (h − 2), since the subtrees of the root’s children should also contain the fewest nodes. As base cases, the fewest nodes in a height-balanced tree of height 0 is one, i.e., F (0) = 1, while the fewest nodes in a height-balanced tree of height 1 is two, i.e., F (1) = 2. Then this recurrence is lower bounded by F (h) ≥ 2h/2 = 2Ω(h) as desired. Recitation 7 2 Rotations As we add or remove nodes to our tree, it is possible that our tree will become imbalanced. We will want to change the structure of the tree without changing its traversal order, in the hopes that we can make the tree’s structure more balanced. We can change the structure of a tree using a local operation called a rotation. A rotation takes a subtree that locally looks like one the following two configurations and modifies the connections between nodes in O(1) time to transform it into the other configuration. 1 2 3 4 5 _______ ____ / \ / \ / \ /___\ /___\ /___\ rotate_right() => <= rotate_left() _______ ____ / \ /___\ / \ / \ /___\ /___\ This operation preserves the traversal order of the tree while changing the depth of the nodes in subtrees and . Next time, we will use rotations to enforce that a balanced tree stays balanced after inserting or deleting a node. 1 2 3 4 5 6 7 8 9 10 11 12 def subtree_rotate_right(D): assert D.left B, E = D.left, D.right A, C = B.left, B.right D, B = B, D D.item, B.item = B.item, D.item B.left, B.right = A, D D.left, D.right = C, E if A: A.parent = B if E: E.parent = D # B.subtree_update() # D.subtree_update() def subtree_rotate_left(B): assert B.right A, D = B.left, B.right C, E = D.left, D.right B, D = D, B B.item, D.item = D.item, D.left, D.right = B, E B.left, B.right = A, C if A: A.parent = B if E: E.parent = D # B.subtree_update() # D.subtree_update() # O(1) B.item # wait for R07! # wait for R07! Maintaining Height-Balance Suppose we have a height-balanced AVL tree, and we perform a single insertion or deletion by adding or removing a leaf. Either the resulting tree is also height-balanced, or the change in leaf has made at least one node in the tree have magnitude of skew greater than 1. In particular, the only nodes in the tree whose subtrees have changed after the leaf modification are ancestors of that leaf (at most O(h) of them), so these are the only nodes whose skew could have changed and they could have changed by at most 1 to have magnitude at most 2. As shown in lecture via a brief case analysis, given a subtree whose root has skew is 2 and every other node in its subtree is height-balanced, we can restore balance to the subtree in at most two rotations. Thus to rebalance the entire tree, it suffices to walk from the leaf to the root, rebalancing each node along the way, performing at most O(log n) rotations in total. A detailed proof is outlined in the lecture notes and is not repeated here; but the proof may be reviewed in recitation if students would like to see the Recitation 7 3 full argument. Below is code to implement the rebalancing algorithm presented in lecture. 1 2 def skew(A): # O(?) return height(A.right) - height(A.left) 3 4 5 6 7 8 9 10 11 12 def rebalance(A): # O(?) if A.skew() == 2: if A.right.skew() < 0: A.right.subtree_rotate_right() A.subtree_rotate_left() elif A.skew() == -2: if A.left.skew() > 0: A.left.subtree_rotate_left() A.subtree_rotate_right() 13 14 15 16 17 def maintain(A): A.rebalance() A.subtree_update() if A.parent: A.parent.maintain() # O(h) Unfortunately, it’s not clear how to efficiently evaluate the skew of a a node to determine whether or not we need to perform rotations, because computing a node’s height naively takes time linear in the size of the subtree. The code below to compute height recurses on every node in ’s subtree, so takes at least Ω(n) time. 1 2 3 def height(A): # Omega(n) if A is None: return -1 return 1 + max(height(A.left), height(A.right)) Rebalancing requires us to check at least Ω(log n) heights in the worst-case, so if we want rebalancing the tree to take at most O(log n) time, we need to be able to evaluate the height of a node in O(1) time. Instead of computing the height of a node every time we need it, we will speed up computation via augmentation: in particular each node stores and maintains the value of its own subtree height. Then when we’re at a node, evaluating its height is a simple as reading its stored value in O(1) time. However, when the structure of the tree changes, we will need to update and recompute the height at nodes whose height has changed. 1 2 3 1 2 def height(A): if A: return A.height else: return -1 def subtree_update(A): # O(1) A.height = 1 + max(height(A.left), height(A.right)) In the dynamic operations presented in R06, we put commented code to call update on every node whose subtree changed during insertions, deletions, or rotations. A rebalancing insertion or deletion operation only calls subtree update on at most O(log n) nodes, so as long as updating a Recitation 7 4 node takes at most O(1) time to recompute augmentations based on the stored augmentations of the node’s children, then the augmentations can be maintained during rebalancing in O(log n) time. In general, the idea behind augmentation is to store additional information at each node so that information can be queried quickly in the future. You’ve done some augmentation already in PS1, where you augmented a singly-linked list with back pointers to make it faster to evaluate a node’s predecessor. To augment the nodes of a binary tree with a subtree property P(), you need to: • clearly define what property of ’s subtree corresponds to P(), and • show how to compute P() in O(1) time from the augmentations of ’s children. If you can do that, then you will be able to store and maintain that property at each node without affecting the O(log n) running time of rebalancing insertions and deletions. We’ve shown how to traverse around a binary tree and perform insertions and deletions, each in O(h) time while also maintaining height-balance so that h = O(log n). Now we are finally ready to implement an efficient Sequence and Set. Binary Node Implementation with AVL Balancing 1 2 3 def height(A): if A: return A.height else: return -1 4 5 6 7 8 9 10 11 class Binary_Node: def __init__(A, x): A.item = x A.left = None A.right = None A.parent = None A.subtree_update() # O(1) 12 13 14 def subtree_update(A): # O(1) A.height = 1 + max(height(A.left), height(A.right)) 15 16 17 def skew(A): # O(1) return height(A.right) - height(A.left) 18 19 20 21 22 def subtree_iter(A): # O(n) if A.left: yield from A.left.subtree_iter() yield A if A.right: yield from A.right.subtree_iter() Recitation 7 5 23 24 25 26 def subtree_first(A): # O(log n) if A.left: return A.left.subtree_first() else: return A 27 28 29 30 def subtree_last(A): # O(log n) if A.right: return A.right.subtree_last() else: return A 31 32 33 34 35 36 def successor(A): # O(log n) if A.right: return A.right.subtree_first() while A.parent and (A is A.parent.right): A = A.parent return A.parent 37 38 39 40 41 42 def predecessor(A): # O(log n) if A.left: return A.left.subtree_last() while A.parent and (A is A.parent.left): A = A.parent return A.parent 43 44 45 46 47 48 49 50 def subtree_insert_before(A, B): if A.left: A = A.left.subtree_last() A.right, B.parent = B, A else: A.left, B.parent = B, A A.maintain() # O(log n) def subtree_insert_after(A, B): if A.right: A = A.right.subtree_first() A.left, B.parent = B, A else: A.right, B.parent = B, A A.maintain() # O(log n) 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 def subtree_delete(A): # O(log n) if A.left or A.right: if A.left: B = A.predecessor() else: B = A.successor() A.item, B.item = B.item, A.item return B.subtree_delete() if A.parent: if A.parent.left is A: A.parent.left = None else: A.parent.right = None A.parent.maintain() return A Recitation 7 74 75 76 77 78 79 80 81 82 83 84 85 def subtree_rotate_right(D): assert D.left B, E = D.left, D.right A, C = B.left, B.right D, B = B, D D.item, B.item = B.item, D.item B.left, B.right = A, D D.left, D.right = C, E if A: A.parent = B if E: E.parent = D B.subtree_update() D.subtree_update() 6 # O(1) 86 87 88 89 90 91 92 93 94 95 96 97 98 def subtree_rotate_left(B): assert B.right A, D = B.left, B.right C, E = D.left, D.right B, D = D, B B.item, D.item = D.item, B.item D.left, D.right = B, E B.left, B.right = A, C if A: A.parent = B if E: E.parent = D B.subtree_update() D.subtree_update() # O(1) 99 100 101 102 103 104 105 106 107 108 def rebalance(A): # O(1) if A.skew() == 2: if A.right.skew() < 0: A.right.subtree_rotate_right() A.subtree_rotate_left() elif A.skew() == -2: if A.left.skew() > 0: A.left.subtree_rotate_left() A.subtree_rotate_right() 109 110 111 112 113 def maintain(A): A.rebalance() A.subtree_update() if A.parent: A.parent.maintain() # O(log n) Recitation 7 7 Application: Set Using our new definition of Binary Node that maintains balance, the implementation presented in R06 of the Binary Tree Set immediately supports all operations in h = O(log n) time, except build(X) and iter() which run in O(n log n) and O(n) time respectively. This data structure is what’s normally called an AVL tree, but what we will call a Set AVL. Application: Sequence To use a Binary Tree to implement a Sequence interface, we use the traversal order of the tree to store the items in Sequence order. Now we need a fast way to find the ith item in the sequence because traversal would take O(n) time. If we knew how many items were stored in our left subtree, we could compare that size to the index we are looking for and recurse on the appropriate side. In order to evaluate subtree size efficiently, we augment each node in the tree with the size of its subtree. A node’s size can be computed in constant time given the sizes of its children by summing them and adding 1. 1 2 3 4 5 6 class Size_Node(Binary_Node): def subtree_update(A): # O(1) super().subtree_update() A.size = 1 if A.left: A.size += A.left.size if A.right: A.size += A.right.size 7 8 9 10 11 12 13 14 def subtree_at(A, i): assert 0 <= i if A.left: else: if i < L_size: elif i > L_size: else: # O(h) L_size L_size return return return = A.left.size = 0 A.left.subtree_at(i) A.right.subtree_at(i - L_size - 1) A Once we are able to find the ith node in a balanced binary tree in O(log n) time, the remainder of the Sequence interface operations can be implemented directly using binary tree operations. Further, via the first exercise in R06, we can build such a tree from an input sequence in O(n) time. We call this data structure a Sequence AVL. Implementations of both the Sequence and Set interfaces can be found on the following pages. We’ve made a CoffeeScript Balanced Binary Search Tree visualizer which you can find here: https://codepen.io/mit6006/pen/NOWddZ Recitation 7 1 2 8 class Seq_Binary_Tree(Binary_Tree): def __init__(self): super().__init__(Size_Node) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 def build(self, X): def build_subtree(X, i, j): c = (i + j) // 2 root = self.Node_Type(A[c]) if i < c: root.left = build_subtree(X, i, c - 1) root.left.parent = root if c < j: root.right = build_subtree(X, c + 1, j) root.right.parent = root root.subtree_update() return root self.root = build_subtree(X, 0, len(X) - 1) self.size = self.root.size 18 19 20 21 def get_at(self, i): assert self.root return self.root.subtree_at(i).item 22 23 24 25 def set_at(self, i, x): assert self.root self.root.subtree_at(i).item = x 26 27 28 29 30 31 32 33 34 35 36 37 38 def insert_at(self, i, x): new_node = self.Node_Type(x) if i == 0: if self.root: node = self.root.subtree_first() node.subtree_insert_before(new_node) else: self.root = new_node else: node = self.root.subtree_at(i - 1) node.subtree_insert_after(new_node) self.size += 1 39 40 41 42 43 44 45 46 def delete_at(self, i): assert self.root node = self.root.subtree_at(i) ext = node.subtree_delete() if ext.parent is None: self.root = None self.size -= 1 return ext.item 47 48 49 50 51 def def def def insert_first(self, x): delete_first(self): insert_last(self, x): delete_last(self): self.insert_at(0, x) return self.delete_at(0) self.insert_at(len(self), x) return self.delete_at(len(self) - 1) Recitation 7 9 Exercise: Make a Sequence AVL Tree or Set AVL Tree (Balanced Binary Search Tree) by inserting student chosen items one by one. If any node becomes height-imbalanced, rebalance its ancestors going up the tree. Here’s a Sequence AVL Tree example that may be instructive (remember to update subtree heights and sizes as you modify the tree!). 1 2 3 4 5 6 7 T = Seq_Binary_Tree() T.build([10,6,8,5,1,3]) T.get_at(4) T.set_at(4, -4) T.insert_at(4, 18) T.insert_at(4, 12) T.delete_at(2) Solution: 1 Line # 2 3 4 5 6 Result 1 | 2,3 | 4 | | None | ___8__ | ___8___ | 10_ _1_ | 10_ _-4_ | 6 5 3 | 6 5 3 | | | 5 | | ___8_____ | 10_ ___-4_ | 6 5__ 3 | 18 7 8 Also labeled with subtree height H, size #: 9 10 11 12 13 None ___________8H2#6__________ 10H1#2_____ _____1H1#3_____ 6H0#1 5H0#1 3H0#1 14 15 16 17 ___________8H2#6__________ 10H1#2_____ _____1H1#3_____ 6H0#1 5H0#1 3H0#1 18 19 20 21 ___________8H2#6___________ 10H1#2_____ _____-4H1#3_____ 6H0#1 5H0#1 3H0#1 22 23 24 25 26 ___________8H3#7_________________ 10H1#2_____ ___________-4H2#4_____ 6H0#1 5H1#2______ 3H0#1 18H0#1 27 28 29 30 31 ___________8H3#8_______________________ 10H1#2_____ ____________-4H2#5_____ 6H0#1 _____12H1#3______ 3H0#1 5H0#1 18H0#1 32 33 34 35 __________12H2#7____________ ______6H1#3_____ ______-4H1#3_____ 10H0#1 5H0#1 18H0#1 3H0#1 | 6 | | ___8_______ | 10_ ____-4_ | 6 _12__ 3 | 5 18 | 7 | | __12____ | __6_ __-4_ | 10 5 18 3 | Recitation 7 10 Exercise: Maintain a sequence of n bits that supports two operations, each in O(log n) time: • flip(i): flip the bit at index i • count ones upto(i): return the number of bits in the prefix up to index i that are one Solution: Maintain a Sequence Tree storing the bits as items, augmenting each node A with A.subtree ones, the number of 1 bits in its subtree. We can maintain this augmentation in O(1) time from the augmentations stored at its children. 1 2 3 4 5 6 def update(A): A.subtree_ones = A.item if A.left: A.subtree_ones += A.left.subtree_ones if A.right: A.subtree_ones += A.right.subtree_ones To implement flip(i), find the ith node A using subtree node at(i) and flip the bit stored at A.item. Then update the augmentation at A and every ancestor of A by walking up the tree in O(log n) time. To implement count ones upto(i), we will first define the subtree-based recursive function subtree count ones upto(A, i) which returns the number of 1 bits in the subtree of node A that are at most index i within A’s subtree. Then count ones upto(i) is symantically equivilent to subtree count ones upto(T.root, i). Since each recursive call makes at most one recursive call on a child, operation takes O(log n) time. 1 2 3 4 5 6 7 8 9 10 11 12 13 def subtree_count_ones_upto(A, i): assert 0 <= i < A.size out = 0 if A.left: if i < A.left.size: return subtree_count_ones_upto(A.left, i) out += A.left.subtree_ones i -= A.left.size out += A.item if i > 0: assert A.right out += subtree_count_ones_upto(A.right, i - 1) return out

6.006 Introduction to Algorithms, Recitation 7

6.006 Introduction to Algorithms, Recitation 7 - Page 1
6.006 Introduction to Algorithms, Recitation 7 - Page 2
6.006 Introduction to Algorithms, Recitation 7 - Page 3
6.006 Introduction to Algorithms, Recitation 7 - Page 4
6.006 Introduction to Algorithms, Recitation 7 - Page 5
6.006 Introduction to Algorithms, Recitation 7 - Page 6
6.006 Introduction to Algorithms, Recitation 7 - Page 7
6.006 Introduction to Algorithms, Recitation 7 - Page 8
6.006 Introduction to Algorithms, Recitation 7 - Page 9
6.006 Introduction to Algorithms, Recitation 7 - Page 10
of 10
0/0
Fair Use Policy

EduBirdie considers academic integrity to be the essential part of the learning process and does not support any violation of the academic standards. Should you have any questions regarding our Fair Use Policy or become aware of any violations, please do not hesitate to contact us via support@edubirdie.com.

logo

Popular Services

  • Essay writing service
  • Pay someone to do my homework
  • Do my assignment for me
  • Research paper writing services
  • Dissertation writing services
  • Do my homework

Study Resources

  • Essay Examples
  • Blog
  • Study Notes

About Us

  • How it works?
  • Testimonials
  • FAQ
  • Money back guarantee

Contact us

mail icon
  • support@edubirdie.com
phone-icon
  • +3 (595) 691 8356
  • +1 (888) 337 5415
DMCA.com Protection Status

For press

  • Press and media
  • Brand assets
Facebook Twitter Instagram LinkedIn

Local sites

  • Ca.EduBirdie.com- The Best Essay Writing Service for Canadian Students

We accept

2024 © EduBirdie.com. All rights reserved

RADIOPLUS EXPERTS LTD. Louki Akrita, 23 Bellapais Court, Flat/Office 46 1100, Nicosia, Cyprus

Privacy Policy
|
Terms of Use
|
Fair use policy
Subscription rules
|
Referral program Rules
|
Payment and Refund Policy
|
Cookie Policy

Report

Tell us what’s wrong with it:

Thanks, got it!
We will moderate it soon!

Report

Tell us what’s wrong with it:

Almost There!

Two easy ways to download this document

or
Upgrade to premium for unlimited access
Calendar Icon

Free up your schedule!

Our EduBirdie Experts Are Here for You 24/7! Just fill out a form and let us know how we can assist you.

Unlock Icon

Take 5 seconds to unlock

Enter your email below and get instant access to your document

This field is required
Please enter a valid email address
This field is required
This field is required

By clicking 'Sign Up', you agree to our Terms and Conditions and Privacy Policy.