Binary Trees

17.2

Binary Trees

Decision Trees

Decision Trees

Balanced Trees

Class Question 1

Consider a binary 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

Size of a binary tree

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;
   }
   . . .
}

Class 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 Computation of height

height(tree) = 1 + max(height(left), height(right))

Class 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 public height method should have been static
  2. The private 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

Class Question 4

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

public class BinaryTree
{
   . . .
   public int height() { return height(root); }
  
   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

Java heading

More about Java.