Tree Traversal

17.4

Tree Traversal

Inorder Tree Traversal

Inorder Traversal Example - print

bst

12/4 Class Question 1

What is the inorder traversal of the tree

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

Print in order

Preorder/Postorder

12/4 Class Question 1

What are preorder and postorder traversals of the tree

   F
  / \
 D   R
  \
   E
  1. FEDR, DEFR
  2. FDER, EDRF
  3. DEFR, ERDF
  4. something else

Postorder Traversal of Expression Tree

Directory Operations

Directory Operations

12/4 Class 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.preorder(v);
   System.out.println("Short names: " + v.counter);
}

Iteration

Depth-First Search

Breadth-First Search

12/4 Class 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;
   }
}