Other 2007 FR Questions FR other years Be Prepared Home
AB-3
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:
  1. It is possible to do this using a stack, but it is easier to use a recursive helper method.

  2. Or:
        TreeNode root = new TreeNode(value);
    due to autoboxing.

Other 2007 FR Questions | Back to Contents

Copyright © 2007 by Skylight Publishing
support@skylit.com