Bstproblems
Bstproblems
1. Write a function which given a binary tree, returns n the number of nodes. Your function should run in time
O(n).
2. Write a function which given a binary tree, returns the number L of leaves in it. Remember that a node is a
leaf if it has no children. Your function should run in time O(L + n).
3. Write a function which given a tree returns a vector v such that v[i] gives the number of nodes at a distance
i from the root. You might find it useful to have two function, one function which the rest of the world calls,
but which in turn calls a recursive function that does all the work. Be careful in specifying which parameters
are passed by reference, if any. Remember that if you pass a vector by value, it is copied and that takes time
proportional to its length. Your function should run in time O(n).
4. An important generic procedure that can be performed on a tree is to traverse it. Here is the skeleton of a
possible traverse function.
6. Write a program which draws the tree such that the x coordinate of each node is proportional to the inorder
number, and y coordinate proportional to the depth. Your function should run in time O(n).
7. Let Rn (i) denote the number obtained by reversing the binary representation of the n bit number i. For
example, R4 (12) is 3, because the binary representations of 12, 3 are 1100, 0011, and thus reverses of each
other. Suppose we have an initially empty search tree into which in step i we insert Rn (i) for i = 1 to
i = 2n − 1. What is the height of this tree?
8. Suppose n distinct numbers are inserted into a binary search tree in a randomly chosen order. What is the
probability that the tree will have height n? Relate this to the operations performed in Quicksort, and assume
that the time for performing Quicksort is O(n log n) if at each stage the pivot is randomly chosen from current
set of keys to be sorted.
9. Suppose we add an integer member size to struct Node. We would like to have the invariant that v.size
is equal to the number of nodes in the subtree beneath node v (including v itself). Show how the insert
function update v.size of relevant nodes suitably so that the invariant is maintained. The insert function
should run in time O(h) as before, where h is the height of the tree.
10. Using the member size as described above, show how to find the rth smallest key in the set, given r and the
root of the tree. Your function should run in time O(h).
11. Give an algorithm that prints the elements in a binary search tree falling in a given interval [a, b]. Your
algorithm should run in time O(h + m), where h is the height of the tree and m is the number of elements in
the set that are in the given interval.
12. Suppose you are given a possibly unbalanced binary search tree on n nodes. Show that in time O(n) you can
construct a binary search tree with the same set of keys having height log n.