Binary Trees

Terminology

Learn all these terms:

The Wonder and Joy of Binary Trees

  1. \(\lfloor \log_2 h \rfloor\)
  2. \(2h + 1\)
  3. \(2^{h+1} - 1\)
  4. \((2h^3 + 3n^2 + n) / 6\)
  5. \(h!\)

The Wonder and Joy of Binary Trees

Exercise #2

  1. \(\lceil \log_2 n \rceil\)
  2. \(\lfloor \log_2 n \rfloor\)
  3. \(\lfloor \frac{n}{2} \rfloor\)
  4. \(n\)
  5. \(2^n\)

Exercise #2

Take Home Message

Pre-Order Traversal

static <E> void preorder(BinNode<E> rt) {
  if (rt == null) { return; } // Empty subtree - do nothing
  visit(rt);              // Process root node
  preorder(rt.left());    // Process all nodes in left
  preorder(rt.right());   // Process all nodes in right
}

In-Order Traversal

static <E> void inorder(BinNode<E> rt) {
  if (rt == null) { return; } // Empty subtree - do nothing
  inorder(rt.left());     // Process all nodes in left
  visit(rt);              // Process root node
  inorder(rt.right());    // Process all nodes in right
}

Post-Order Traversal

static <E> void postorder(BinNode<E> rt) {
  if (rt == null) { return; } // Empty subtree - do nothing
  postorder(rt.left());    // Process all nodes in left
  postorder(rt.right());   // Process all nodes in right
  visit(rt);               // Process root node
}

Another Traversal

Trace the following traversal method…

  public static <E> void mystery(BinNode<E> rt) {
    Queue<BinNode<E>> queue = new LQueue<>();

    queue.enqueue(rt);

    while (queue.length() > 0) {
      BinNode<E> cur = queue.dequeue();

      visit(cur);

      if (cur.left() != null) {
        queue.enqueue(cur.left());
      }
      if (cur.right() != null) {
        queue.enqueue(cur.right());
      }
    }

  }