Exemplo n.º 1
0
  /** Prints the keys of the tree in the order given by a level-order traversal. */
  public void levelOrderPrint() {
    LLQueue<NodePlusDepth> q = new LLQueue<NodePlusDepth>();

    // Insert the root into the queue if the root is not null.
    if (root != null) q.insert(new NodePlusDepth(root, 0));

    // We continue until the queue is empty.  At each step,
    // we remove an element from the queue, print its value,
    // and insert its children (if any) into the queue.
    // We also keep track of the current level, and add a newline
    // whenever we advance to a new level.
    int level = 0;
    while (!q.isEmpty()) {
      NodePlusDepth item = q.remove();

      if (item.depth > level) {
        System.out.println();
        level++;
      }
      System.out.print(item.node.key + " ");

      if (item.node.left != null) q.insert(new NodePlusDepth(item.node.left, item.depth + 1));
      if (item.node.right != null) q.insert(new NodePlusDepth(item.node.right, item.depth + 1));
    }
  }
Exemplo n.º 2
0
 private LLQueue getLLQueue() {
   return LLQueue.get();
 }