Practice with Recursion

Assume that binary trees are implemented using the following definition:


Question 1:

Write method sum, whose header is given below. Method sum should return the sum of the values stored in the tree rooted at node T.

static int sum(Treenode T)

Question 2:

Write method allLess, whose header is given below. Method allLess should return true iff all of the nodes in the tree rooted at T have values smaller than k.

static boolean allLess(Treenode T, int k)

Question 3:

Assume that method height, whose header is given below, has been written.

static int height(Treenode T)
// postcondition: returns the height of the tree rooted at T
//                if T is null, its height is 0
Write method almostBalanced, whose header is given below. Method almostBalanced should return true iff, for all nodes in the tree rooted at T, the height of T's two subtrees differ by at most 1.
static boolean almostBalanced(Treenode T)

Question 4:

Recall that the depth of a node n in a tree is the number of nodes on the path from the root to node n. Write method recordDepth, whose header is given below. Method recordDepth should determine the depth of each node in the tree rooted at T, and should record that value in the node's "data" field. Hint: Use an auxiliary method with a second parameter.

static void recordDepth(Treenode T)

Assume that linked lists are implemented using the following definition.


Question 5:

Write method sum, whose header is given below. Method sum should use recusion to compute and return the sum of the values in the list pointed to by L.

static int sum(Listnode L)

Question 6:

Write method sameLists, whose header is given below. Method sameLists should use recusion to determine whether the lists pointed to by L1 and L2 are the same (have the same number of nodes, and have the same values in all corresponding nodes).

static boolean sameLists(Listnode L1, Listnode L2)