CS 3345 – Spring 2012Homework 3 Solutions
Q1.
a. Algorithm: preorderNext (node v)Input: the current node vOutput: the next node in the preorder traversal of T
Pseudocode:
if v is internal thenreturn v’s left child
elsenode p = parent of v
if v is left child of p thenreturn right child of p
else while v is not a left child of p and p is not root do
v = pp = p.parent
end whilereturn right child of p
end ifend if
1
b. Algorithm: inOrderNext (node v)Input: the current node vOutput: the next node in the in order traversal of T
Pseudocode:
if v is an internal node thencurrent v.rightwhile current has a left child do
current current.leftreturn current
elsecurrent vp current.parentwhile current is the right child of p do
if p = root thenreturn null
else current pp current.parent
end ifend whilereturn p
end if
c. For this algorithm, we assume that the Boolean methods isRightChild () and isLeftChild () already exist as part of the implementation of a node
2
Algorithm: postOrderNext (node v)Input: the current node vOutput: the next node in the postorder traversal of T
Pseudocode:
if v is an internal node thenif v is a right child then
return v.parentelse
v (v.parent).right
while v is an internal node dov v.left
end whilereturn v
end ifelse
if v is a right child thenreturn v.parent
elsev (v.parent).right
while v is an internal node doif v.left is not null then
v v.leftelse
v v.rightend if
end whilereturn v
end ifend if
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
3
b. The diameter of the subtree with (T.root).right as its rootc. 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 vOutput: The diameter of a tree T with v as its root
Pseudocode:
if v = null thenreturn 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)
Q3.
4
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 iOutput: a sorted list with the top log n frequent flyers
Pseudocode:
Let L be a new listH BottomUpHeap (A)
for n = 0 to log n doa H.removeMin ()L.insertLast (a)
end forreturn L
Q5.
The hash table using linear probing:
Key 11 43 33 13 14 16 12 3 22 - 10Position 0 1 2 3 4 5 6 7 8 9 10
The hash table using double hashing:
Key 11 43 33 14 13 16 22 12 - 3 10Position 0 1 2 3 4 5 6 7 8 9 10
7
Q6.
8