| | | | | |

Maintaining Threads (with possible dead nodes)

Non-threaded code:

template <typename T, class P>
T& BST<T,P>::Get (const T& t)
{
  if (root_ == nullptr)
  {
    root_ = NewNode(t);
    return root_->value_;
  }
  Node * p = nullptr;  // trailing parent
  Node * n = root_;
  bool   left;
  while (n != nullptr)
  {
    p = n;
    if (pred_(t,n->value_))
    {
      n = n->lchild_;
      left = 1;
    }
    else if  (pred_(n->value_,t))
    {
      n = n->rchild_;
      left = 0;
    }
    else // found
    {
      n->SetAlive();
      return n->value_;
    }
  }
  n = NewNode(t);
  (left ? p->lchild_ = n : p->rchild_ = n);
  return n->value_;
}

Threaded Code:

{
  ...
  Node * p = nullptr;  // trailing parent
  Node * n = root_;
  bool finished = 0;
  do
  {
    p = n;
    if (pred_(t,n->value_))  // t < n->value_
    {
      if (n->HasLeftChild())   // n->lchild_ is an actual child node of n
      {
        n = n->lchild_;          // go to that child
      }
      else                     // n->lchild_ is the previous "inorder" node to n
      {
        n = NewNode(t, THREADS); // recall p = "old" n
        n->SetLeftThread(p->lchild_);
        n->SetRightThread(p);
        p->SetLeftChild(n);
        finished = 1;            // added node at bottom of tree
      }
    }
    else if  (pred_(n->value_,t))
    {
      ...
    }
    else // found
    {
      n->SetAlive();
      finished = 1;
    }
  }
  while (!finished);
  return n->value_;
}

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