12b: BST Iterators and Tree Searching

ICS211, Spring 2013
Dr. Zach

(switch view)

Status

BST Performance

Good BSTs need to be balanced

BST as a SortedList replacement / implementation

Designing Attempt

Iterator

Binary Trees

General binary trees

Creation / Addition

Removal

Traversals

Searching

Depth-First Search (DFS)

  /** 
   * Returns the first element found that is equal to elem in the tree
   * rooted at node.  Uses a depth-first search.  If no equal is found, 
   * returns null.
   */
  public static <E> E dfs(E elem, TreeNode<E> node) {
    Deque<TreeNode<E>> stack = new ArrayDeque<TreeNode<E>>();
    stack.push(node);
    while (!stack.isEmpty()) {
      TreeNode<E> curr = stack.pop();
      System.out.println(curr.getData());
      if (curr.getData().equals(elem)) {
        //found it
        return elem;
      }
      if (curr.getRight() != null) {
        stack.push(curr.getRight());
      }
      if (curr.getLeft() != null) {
        stack.push(curr.getLeft());
      }
    }
    //out of nodes, but never returned from in loop
    return null;
  }

Breadth-First Search (BFS)

 /** 
   * Returns the first element found that is equal to elem in the tree
   * rooted at node.  Uses a breadth-first search.  If no equal is found, 
   * returns null.
   */
  public static <E> E bfs(E elem, TreeNode<E> node) {
    Queue<TreeNode<E>> queue = new ArrayDeque<TreeNode<E>>();
    queue.offer(node);
    while (!queue.isEmpty()) {
      TreeNode<E> curr = queue.poll();
      System.out.println(curr.getData());
      if (curr.getData().equals(elem)) {
        //found it
        return elem;
      }
      if (curr.getLeft() != null) {
        queue.offer(curr.getLeft());
      }
      if (curr.getRight() != null) {
        queue.offer(curr.getRight());
      }
    }
    //out of nodes, but never returned from in loop
    return null;
  }

Searching

For next time...