CS 46B - Lecture 25

Cover page image

Pre-class reading

Tree Traversal

Preorder/Postorder

Lecture 25 Clicker Question 1

What are inorder, preorder,  and postorder traversals of the tree

   F
  / \
 D   R
  \
   E
  1. DEFR, FEDR, EDRF
  2. EDFR, FDER, EDRF
  3. DEFR, FDER, DERF
  4. Something else

Postorder Traversal of Expression Tree

Directory Operations

Directory Operations

Lecture 25 Clicker Question 2

Suppose you have two directory trees and you want to find out whether they contain the same  subdirectories, each of which contains the same files. Should you traverse using

  1. inorder
  2. preorder
  3. postorder
  4. preorder or postorder

Visitor Pattern

Example: Count Short Names

public static void main(String[] args)
{
   BinarySearchTree bst = . . .;
   class ShortNameCounter implements Visitor
   {
      public int counter = 0;
      public void visit(Object data)
      {
         if (data.toString().length() <= 5) { counter++; }
      }
   }
   ShortNameCounter v = new ShortNameCounter();
   bst.inorder(v);
   System.out.println("Short names: " + v.counter);
}

Iteration

Depth-First Search

Breadth-First Search

Lecture 25 Clicker Question 3

Suppose you have a binary tree of height n > 1.  Can its depth-first traversal ever be the same as its breadth-first traversal?

  1. No, never
  2. Yes, if it's not a binary search tree
  3. Yes, if it has n elements
  4. Yes, if the height is 2

Tree Iterators

Tree Iterators

class BreadthFirstIterator
{
   private Queue<Node> q;
   public BreadthFirstIterator(Node root)
   {
      q = new LinkedList<Node>();
      if (root != null) { q.add(root); }
   }
   public boolean hasNext() { return q.size() > 0; }
   public Object next()
   {
      Node n = q.remove();
      for (Node c : n.children) { q.add(c); }
      return n.data;
   }
}

A Look Back on CS46B

What Really Matters

Next Semester

I Wish This Slide Wasn't Here

What Really Matters