| | | | | |

Binary Tree Iterator Algorithms: Postorder

Initialize(bt)
{
  n = bt.root;                             // always enter tree at root
  while (1)                                // descend to bottom with left priority
  {
    if (n->HasLeftChild()) 
      ++n;
    else if (n->HasRightChild())
      n++;
    else
      break;
  }
  while (n->IsDead()) Increment();         // skip dead nodes
}

Increment()
{
  bool wasLeftChild = n->IsLeftChild();    // remember upward direction
  --n;                                     // ascend to parent
  if (wasLeftChild && n->HasRightChild())  // if n was right child and has right child
  {
    n++;                                   // go there
    while (1)                              // descend to bottom with left priority
    {
      if (n->HasLeftChild())
        ++n;
      else if (n->HasRightChild())
        n++;
      else
        break;
    }
  }
}

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