July 18, 2009
This is a collection of some interesting problems, carefully collected to help you prepare better for the midterm and, which is more important, help you in understanding of the key concepts.
Try to solve them independently or with your friends.
Review problem 1 How many di®erent binary search trees can store the keys f1;2;3g? The same question for f1;2;3;4g.
Solution: For the ¯rst: 5. The second: there are 5 possibilities each when
1 and 4 are the root of tree. If 2 is the root of the tree, there are 2 di®erent
BSTs. The same when 3 is the root. In total, 14.
Review problem 2 Insert, into an empty binary search trees, entries with keys 30, 40, 24, 58, 48, 26, 11, 13 (in this order). Draw the tree after each insertion. Review problem 3 By giving an example, prove that the following claim is false: the order in which a ¯xed set of entries is inserted into a BST does not matter- the same tree results every time.
Review problem 4 In this problem you will design a linear-time algorithm that clones a binary tree T. This algorithm should construct an exact copy of
T. You are only allowed to use the methods of the Tree and Binary Tree ADTs
(i.e. isEmpty, root, parent, children, isInternal, isExternal, isRoot, size, elements, positions, swapElements, replaceElement, leftChild, rightChild, sibling, expandExternal, removeAboveExternal).
Describe (in pseudo-code) your algorithm.
1Hint: Do preorder traversal of the corresponding trees.
Review problem 5 Describe how to perform an operation removeAll(k), which removes all the entries whose keys equal k from a BST T.
Review problem 6 Give a recursive method for removing all the elements in a stack.
Solution: If the stack is empty return empty. Otherwise, pop() and recur.
Review problem 7 Describe the output of the following series of stack op- erations: push(5), push(3), pop(), push(2), push(8), pop(), pop(), push(9), push(1), pop(), push(7), push(6), pop(),