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 6

  • University:

    Massachusetts Institute of Technology
  • Course:

    6.006 | Introduction to Algorithms
  • Academic year:

    2020

  • Views:

    266

    Pages:

    8

  • Author:

    paulzjm

  • Last update:

    12.12.2024

Introduction to Algorithms: 6.006 Massachusetts Institute of Technology Instructors: Erik Demaine, Jason Ku, and Justin Solomon Recitation 6 Recitation 6 Binary Trees A binary tree is a tree (a connected graph with no cycles) of binary nodes: a linked node container, similar to a linked list node, having a constant number of fields: • a pointer to an item stored at the node, • a pointer to a parent node (possibly None), • a pointer to a left child node (possibly None), and • a pointer to a right child node (possibly None). 1 2 3 4 5 6 7 class Binary_Node: def __init__(A, x): A.item = x A.left = None A.right = None A.parent = None # A.subtree_update() # O(1) # wait for R07! Why is a binary node called “binary”? In actuality, a binary node can be connected to three other nodes (its parent, left child, and right child), not just two. However, we will differentiate a node’s parent from it’s children, and so we call the node “binary” based on the number of children the node has. A binary tree has one node that that is the root of the tree: the only node in the tree lacking a parent. All other nodes in the tree can reach the root of the tree containing them by traversing parent pointers. The set of nodes passed when traversing parent pointers from node back to the root are called the ancestors for in the tree. The depth of a node in the subtree rooted at is the length of the path from back to . The height of node is the maximum depth of any node in the subtree rooted at . If a node has no children, it is called a leaf. Why would we want to store items in a binary tree? The difficulty with a linked list is that many linked-list nodes can be O(n) pointer hops away from the head of the list, so it may take O(n) time to reach them. By contrast, as we’ve seen in earlier recitations, it is possible to construct a binary tree on n nodes such that no node is more than O(log n) pointer hops away from the root, i.e., there exist binary trees with logarithmic height. The power of a binary tree structure is if we can keep the height h of the tree low, i.e., O(log n), and only perform operations on the tree that run in time on the order of the height of the tree, then these operations will run in O(h) = O(log n) time (which is much closer to O(1) than to O(n)). Recitation 6 2 Traversal Order The nodes in a binary tree have a natural order based on the fact that we distinguish one child to be left and one child to be right. We define a binary tree’s traversal order based on the following implicit characterization: • every node in the left subtree of node comes before in the traversal order; and • every node in the right subtree of node comes after in the traversal order. Given a binary node , we can list the nodes in ’s subtree by recursively listing the nodes in ’s left subtree, listing itself, and then recursively listing the nodes in ’s right subtree. This algorithm runs in O(n) time because every node is recursed on once doing constant work. 1 2 3 4 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() Right now, there is no semantic connection between the items being stored and the traversal order of the tree. Next time, we will provide two different semantic meanings to the traversal order (one of which will lead to an efficient implementation of the Sequence interface, and the other will lead to an efficient implementation of the Set interface), but for now, we will just want to preserve the traversal order as we manipulate the tree. Tree Navigation Given a binary tree, it will be useful to be able to navigate the nodes in their traversal order efficiently. Probably the most straight forward operation is to find the node in a given node’s subtree that appears first (or last) in traversal order. To find the first node, simply walk left if a left child exists. This operation takes O(h) time because each step of the recursion moves down the tree. Find the last node in a subtree is symmetric. 1 2 3 def subtree_first(A): # O(h) if A.left: return A.left.subtree_first() else: return A 4 5 6 7 def subtree_last(A): # O(h) if A.right: return A.right.subtree_last() else: return A Given a node in a binary tree, it would also be useful too find the next node in the traversal order, i.e., the node’s successor, or the previous node in the traversal order, i.e., the node’s predecessor. To find the successor of a node , if has a right child, then ’s successor will be the first node in the right child’s subtree. Otherwise, ’s successor cannot exist in ’s subtree, so we walk up the tree to find the lowest ancestor of such that is in the ancestor’s left subtree. Recitation 6 3 In the first case, the algorithm only walks down the tree to find the successor, so it runs in O(h) time. Alternatively in the second case, the algorithm only walks up the tree to find the successor, so it also runs in O(h) time. The predecessor algorithm is symmetric. 1 2 3 4 5 def successor(A): # O(h) if A.right: return A.right.subtree_first() while A.parent and (A is A.parent.right): A = A.parent return A.parent 6 7 8 9 10 11 def predecessor(A): # O(h) if A.left: return A.left.subtree_last() while A.parent and (A is A.parent.left): A = A.parent return A.parent Dynamic Operations If we want to add or remove items in a binary tree, we must take care to preserve the traversal order of the other items in the tree. To insert a node before a given node in the traversal order, either node has a left child or not. If does not have a left child, than we can simply add as the left child of . Otherwise, if has a left child, we can add as the right child of the last node in ’s left subtree (which cannot have a right child). In either case, the algorithm walks down the tree at each step, so the algorithm runs in O(h) time. Inserting after is symmetric. 1 2 3 4 5 6 7 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(h) # wait for R07! 8 9 10 11 12 13 14 15 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(h) # wait for R07! To delete the item contained in a given node from its binary tree, there are two cases based on whether the node storing the item is a leaf. If the node is a leaf, then we can simply clear the child pointer from the node’s parent and return the node. Alternatively, if the node is not a leaf, we can swap the node’s item with the item in the node’s successor or predecessor down the tree until the item is in a leaf which can be removed. Since swapping only occurs down the tree, again this operation runs in O(h) time. Recitation 6 1 2 3 4 5 6 7 8 9 10 11 4 def subtree_delete(A): # O(h) if A.left or A.right: # A is not a leaf 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: # A is a leaf if A.parent.left is A: A.parent.left = None else: A.parent.right = None # A.parent.maintain() # wait for R07! return A Binary Node Full Implementation 1 2 3 4 5 6 7 class Binary_Node: def __init__(A, x): A.item = x A.left = None A.right = None A.parent = None # A.subtree_update() # O(1) # wait for R07! 8 9 10 11 12 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() 13 14 15 16 def subtree_first(A): # O(h) if A.left: return A.left.subtree_first() else: return A 17 18 19 20 def subtree_last(A): # O(h) if A.right: return A.right.subtree_last() else: return A 21 22 23 24 25 26 def successor(A): # O(h) if A.right: return A.right.subtree_first() while A.parent and (A is A.parent.right): A = A.parent return A.parent 27 28 29 30 31 32 33 def predecessor(A): # O(h) if A.left: return A.left.subtree_last() while A.parent and (A is A.parent.left): A = A.parent return A.parent Recitation 6 34 35 36 37 38 39 40 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() 5 # O(h) # wait for R07! 41 42 43 44 45 46 47 48 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(h) # wait for R07! 49 50 51 52 53 54 55 56 57 58 59 60 def subtree_delete(A): # O(h) 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() # wait for R07! return A Top-Level Data Structure All of the operations we have defined so far have been within the Binary Tree class, so that they apply to any subtree. Now we can finally define a general Binary Tree data structure that stores a pointer to its root, and the number of items it stores. We can implement the same operations with a little extra work to keep track of the root and size. 1 2 3 4 5 class Binary_Tree: def __init__(T, Node_Type = Binary_Node): T.root = None T.size = 0 T.Node_Type = Node_Type 6 7 8 9 10 11 def __len__(T): return T.size def __iter__(T): if T.root: for A in T.root.subtree_iter(): yield A.item Recitation 6 6 Exercise: Given an array of items A = (a0 , . . . , an−1 ), describe a O(n)-time algorithm to construct a binary tree T containing the items in A such that (1) the item stored in the ith node of T ’s traversal order is item ai , and (2) T has height O(log n). Solution: Build T by storing the middle item in a root node, and then recursively building the remaining left and right halves in left and right subtrees. This algorithm satisfies property (1) by definition of traversal order, and property (2) because the height roughly follows the recurrence H(n) = 1 + H(n/2). The algorithm runs in O(n) time because every node is recursed on once doing constant work. 1 2 3 4 5 6 7 8 9 10 11 12 13 def build(X): A = [x for x in X] def build_subtree(A, i, j): c = (i + j) // 2 root = self.Node_Type(A[c]) if i < c: # needs to store more items in left subtree root.left = build_subtree(A, i, c - 1) root.left.parent = root if c < j: # needs to store more items in right subtree root.right = build_subtree(A, c + 1, j) root.right.parent = root return root self.root = build_subtree(A, 0, len(A)-1) Exercise: Argue that the following iterative procedure to return the nodes of a tree in traversal order takes O(n) time. 1 2 3 4 5 def tree_iter(T): node = T.subtree_first() while node: yield node node = node.successor() Solution: This procedure walks around the tree traversing each edge of the tree twice: once going down the tree, and once going back up. Then because the number of edges in a tree is one fewer than the number of nodes, the traversal takes O(n) time. Recitation 6 7 Application: Set To use a Binary Tree to implement a Set interface, we use the traversal order of the tree to store the items sorted in increasing key order. This property is often called the Binary Search Tree Property, where keys in a node’s left subtree are less than the key stored at the node, and keys in the node’s right subtree are greater than the key stored at the node. Then finding the node containing a query key (or determining that no node contains the key) can be done by walking down the tree, recursing on the appropriate side. Exercise: Make a Set Binary Tree (Binary Search Tree) by inserting student-chosen items one by one, then searching and/or deleting student-chosen keys one by one. 1 2 3 4 5 6 7 8 class BST_Node(Binary_Node): def subtree_find(A, k): # O(h) if k < A.item.key: if A.left: return A.left.subtree_find(k) elif k > A.item.key: if A.right: return A.right.subtree_find(k) else: return A return None 9 10 11 12 13 14 15 16 17 def subtree_find_next(A, k): # O(h) if A.item.key <= k: if A.right: return A.right.subtree_find_next(k) else: return None elif A.left: B = A.left.subtree_find_next(k) if B: return B return A 18 19 20 21 22 23 24 25 26 def subtree_find_prev(A, k): # O(h) if A.item.key >= k: if A.left: return A.left.subtree_find_prev(k) else: return None elif A.right: B = A.right.subtree_find_prev(k) if B: return B return A 27 28 29 30 31 32 33 34 35 def subtree_insert(A, B): # O(h) if B.item.key < A.item.key: if A.left: A.left.subtree_insert(B) else: A.subtree_insert_before(B) elif B.item.key > A.item.key: if A.right: A.right.subtree_insert(B) else: A.subtree_insert_after(B) else: A.item = B.item Recitation 6 1 2 class Set_Binary_Tree(Binary_Tree): # Binary Search Tree def __init__(self): super().__init__(BST_Node) 3 4 def iter_order(self): yield from self 5 6 7 def build(self, X): for x in X: self.insert(x) 8 9 10 def find_min(self): if self.root: return self.root.subtree_first().item 11 12 13 def find_max(self): return self.root.subtree_last().item if self.root: 14 15 16 17 18 def find(self, k): if self.root: node = self.root.subtree_find(k) if node: return node.item 19 20 21 22 23 def find_next(self, k): if self.root: node = self.root.subtree_find_next(k) if node: return node.item 24 25 26 27 28 def find_prev(self, k): if self.root: node = self.root.subtree_find_prev(k) if node: return node.item 29 30 31 32 33 34 35 36 37 38 def insert(self, x): new_node = self.Node_Type(x) if self.root: self.root.subtree_insert(new_node) if new_node.parent is None: return False else: self.root = new_node self.size += 1 return True 39 40 41 42 43 44 45 46 47 def delete(self, k): assert self.root node = self.root.subtree_find(k) assert node ext = node.subtree_delete() if ext.parent is None: self.root = None self.size -= 1 return ext.item 8

6.006 Introduction to Algorithms, Recitation 6

6.006 Introduction to Algorithms, Recitation 6 - Page 1
6.006 Introduction to Algorithms, Recitation 6 - Page 2
6.006 Introduction to Algorithms, Recitation 6 - Page 3
6.006 Introduction to Algorithms, Recitation 6 - Page 4
6.006 Introduction to Algorithms, Recitation 6 - Page 5
6.006 Introduction to Algorithms, Recitation 6 - Page 6
6.006 Introduction to Algorithms, Recitation 6 - Page 7
6.006 Introduction to Algorithms, Recitation 6 - Page 8
of 8
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.