CS 3345 – Spring 2012 Homework 3 Solutions Q1. a. Algorithm: preorderNext (node v) Input: the current node v Output: the next node in the preorder traversal of T Pseudocode: if v is internal then return v’s left child else node p = parent of v if v is left child of p then return right child of p else while v is not a left child of p and p is not root do v=p p = p.parent end while return right child of p end if end if 1 b. Algorithm: inOrderNext (node v) Input: the current node v Output: the next node in the in order traversal of T Pseudocode: if v is an internal node then current v.right while current has a left child do current current.left return current else current v p current.parent while current is the right child of p do if p = root then return null else current p p current.parent end if end while return p end if 2 c. For this algorithm, we assume that the Boolean methods isRightChild () and isLeftChild () already exist as part of the implementation of a node Algorithm: postOrderNext (node v) Input: the current node v Output: the next node in the postorder traversal of T Pseudocode: if v is an internal node then if v is a right child then return v.parent else v (v.parent).right while v is an internal node do v v.left end while return v end if else if v is a right child then return v.parent else v (v.parent).right while v is an internal node do if v.left is not null then v v.left else v v.right end if end while return v end if end if 3 Q2. The diameter of the tree will be the maximum of three numbers: a. The diameter of the subtree with (T.root).left as its root b. The diameter of the subtree with (T.root).right as its root c. The maximum length of a path between nodes that goes through T.root This algorithm should be called with T.root. It runs in O(n2) time. Algorithm: findDiameter (node v) Input: A node v Output: The diameter of a tree T with v as its root Pseudocode: if v = null then return 0 end if leftHeight getHeight (v.left) rightHeight getHeight (v.right) leftDiameter findDiameter (v.left) rightDiameter finDiameter (v.right) return max (leftHeight + rightHeight + 1, leftDiameter, rightDiameter) 4 Q3. 5 6 Q4. The following algorithm runs in O(n) time. The BottomUpHeap () method requires O(n) operations and the for loop will take at most log2n operations. This gives us a O(n + log2n) = O(n) run-time. Algorithm: sortFlyers (A) Input: an array A of size n where A[i] contains the frequent flyer miles of flyer i Output: a sorted list with the top log n frequent flyers Pseudocode: Let L be a new list H BottomUpHeap (A) for n = 0 to log n do a H.removeMin () L.insertLast (a) end for return L Q5. The hash table using linear probing: Key 11 Position 0 43 1 33 2 13 3 14 4 16 5 12 6 3 7 22 8 9 10 10 16 5 22 6 12 7 8 3 9 10 10 The hash table using double hashing: Key 11 Position 0 43 1 33 2 14 3 13 4 7 Q6. 8