Part (a)
/** @param current the root of the subtree to be processed
* @return the maximum path score for the subtree rooted at current
*/
private int getMaxHelper(TreeNode current)
{
if (current == null)
return 0;
int leftScore = getMaxHelper(current.getLeft());
int rightScore = getMaxHelper(current.getRight());
return ((Integer)current.getValue()).intValue() + Math.max(leftScore, rightScore);
}
Part (b)
/** Creates a full binary tree rooted at root with numLevels levels
* with a random integer from 0 to 9, inclusive, generated for each node
* @param numLevels the number of levels in the tree
* Precondition: numLevels > 0
*/
public GameBoard(int numLevels)
{
root = buildTree(numLevels); 1
}
private TreeNode buildTree(int numLevels)
{
int value = (int)(10 * Math.random());
TreeNode root = new TreeNode(new Integer(value)); 2
if (numLevels > 1)
{
root.setLeft(buildTree(numLevels - 1));
root.setRight(buildTree(numLevels - 1));
}
return root;
}
Notes:
- It is possible to do this using a stack, but it is
easier to use a recursive helper method.
- Or:
TreeNode root = new TreeNode(value);
due to autoboxing.
|