This preview shows pages 1–2. Sign up to view the full content.
Data Structures & Algorithms
Exam 2, Sample 2
75 Minutes
Solutions
1.
(a)
To implement a recursive strategy, we need to define a public and a private
elementAtLevel
method. The public method can be defined as below:
/** @return an element at level theLevel */
public Object elementAtLevel(int theLevel)
{return elementAtLevel(root, theLevel);}
The private method that does the actual search for an element at the desired level.
/** @return an element at level theLevel of subtree rooted at t
*/
private static Object elementAtLevel(BinaryTreeNode t, int
theLevel)
{
if (t == null)
// empty tree, no element at level theLevel
return null;
if (theLevel == 1)
// t is at level 1
return t.element;
// search for desired element in left subtree
Object x = elementAtLevel(t.leftChild, theLevel  1);
if (x != null)
// found an element at level theLevel
return x;
// return desired element from right subtree
return elementAtLevel(t.rightChild, theLevel  1);
}
(b)
Each node of the binary tree is reached at most once and a constant amount of
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview. Sign up
to
access the rest of the document.
This note was uploaded on 12/02/2009 for the course EEL 3472 taught by Professor Rakov during the Spring '08 term at University of Florida.
 Spring '08
 RAKOV
 Electromagnet

Click to edit the document details