| | | | | |

Binary Tree Iterator Algorithms: Preorder

Initialize(bt)
{
  n = bt.root;                       // always enter tree at root
  while (n->IsDead()) Increment();   // skip dead nodes
}

Increment()
{
  if (n->HasLeftChild())
  {
    ++n;                             // go to left child
  }
  else if (n->HasRightChild())
  {
    n++;                             // go to right child
  }
  else
  {
    while (n->IsValid())             // ascend until an unvisited right child is found
    {
      prev = n;
      --n;
      if ((prev == n.lchild_) && n->HasRightChild())
      {
        n++;                         // go to right child
        break;                       // and halt
      }
      else
      {
        prev = n;
        --n;                         // keep ascending
      }
    }
  }
}

| | Top of Page | 14. BST Iterators - 5 of 41