CS 46B - Lecture 21

Cover page image

Pre-class reading

Trees

Tree Concepts

Lecture 21 Clicker Question 1

Look at the subtree with root Elizabeth II. Which of the following is true?

  1. That tree has height 3
  2. That tree has 5 interior nodes
  3. That tree has 14 leaves
  4. None of the above

Tree Implementation

public class Tree
{
   private Node root;

   class Node
   {
      public Object data;
      public List<Node> children;
   }

   public Tree(Object rootData)
   {
      root = new Node();
      root.data = rootData;
      root.children = new ArrayList<Node>();
   }

   public void addSubtree(Tree subtree)
   {
      root.children.add(subtree.root);
   }
   . . .
}

Lecture 21 Clicker Question 2

What are the leaves of the tree r?

Tree u = new Tree("Fred");
Tree t = new Tree("Barney");
Tree s = new Tree("Dino");
Tree r = new Tree("Wilma");
r.addSubtree(s);
s.addSubtree(t);
s.addSubtree(u);
  1. Wilma
  2. Fred
  3. Barney
  4. Barney and Fred

Recursive Computations

class Tree
{
   . . .
   class Node
   {
      . . .
      public int size()
      {
         int sum = 0;
         for (Node child : children) { sum = sum + child.size(); }
         return 1 + sum;
      }
   }

   public int size()
   {
      if (root == null) { return 0; }
      else { return root.size(); }
   }
}

Lecture 21 Clicker Question 3

What is correct about this implementation of the height method of a Tree class?

public class Tree
{
   . . .
   public int height() { return root.height(); }
   class Node
   {
      int height()
      {
          int h = 0;
          for (Node child : children) { h = Math.max(h, child.height()); }
          return h + 1;
      }
   }
   . . .
}
  1. The method works correctly
  2. The method works incorrectly for all trees
  3. The method works incorrectly for all non-empty trees
  4. The method works incorrectly for empty trees

Lecture 21 Clicker Question 4

What is true about this implementation of the height methodof a Tree class?

public class Tree
{
   . . .
   public int height() { if (root == null) { return 1; } else { return root.height(); } }
   class Node
   {
      int height()
      {
          int h = 0;
          for (Node child : children) { h = Math.max(h, child.height()); }
          return h;
      }
   }
   . . .
}
  1. The method works correctly
  2. The method works incorrectly for all trees
  3. The method works incorrectly for all non-empty trees
  4. The method works incorrectly for empty trees

Lecture 21 Clicker Question 5

What is the big-oh efficiency of size() and height() in terms of n, the number of nodes in the tree?

  1. O(log n)
  2. O(n)
  3. O(n2)
  4. something else