CS 46B - Lecture 22

Cover page image

Pre-class reading

Binary Trees

Decision Trees

Balanced Trees

Lecture 22 Clicker Question 1

Consider a tree of height h. What is the smallest number of leaves that the tree can have?

  1. 1
  2. h
  3. 2h - 1
  4. 2h - 1

Binary Tree Implementation

public class BinaryTree
{
   private Node root;
   public BinaryTree() { root = null; } // An empty tree
   public BinaryTree(Object rootData, BinaryTree left, BinaryTree right)
   {
      root = new Node();
      root.data = rootData;
      root.left = left.root;
      root.right = right.root;
   }
   class Node
   {
      public Object data;
      public Node left;
      public Node right;
   }
   . . .
}

Lecture 22 Clicker Question 2

What are the leaves of the tree

new BinaryTree("Fred", 
   new BinaryTree("Barney", null, null),
   new BinaryTree("Dino", 
      new BinaryTree("Wilma", null, null),
      null));
  1. Fred
  2. Wilma
  3. Barney and Wilma
  4. Something else

Recursive Computations

Lecture 22 Clicker Question 3

What is wrong with this implementation of the height method of a BinaryTree class?

public class BinaryTree
{
   . . .
   public int height() { return height(root); }
   class Node
   {
      private int height(Node n)
      {
         if (n == null) { return 0; }
         else { return 1 + Math.max(height(n.left), height(n.right)); }
      }
   }
   . . .
}
  1. The private height method should have been static
  2. The public height method should have been static
  3. The returned values are off by one from the actual heights
  4. There is nothing wrong--the method works correctly

Lecture 22 Clicker Question 4

What is wrong with this implementation of the height methodof a BinaryTre class?

public class BinaryTree
{
   . . .
   public int height() { return height(root); }
   class Node 
   {
      private static int height(Node n)
      {
         if (n == null) { return 0; }
         else { return Math.max(height(n.left), height(n.right)); }
      }
   }
   . . .
}
  1. The public height method should have been static
  2. The method returns the wrong value for every tree
  3. The method returns the wrong value for every non-empty tree
  4. There is nothing wrong--the method works correctly