| | | | | |

Implementing Get: Successful Search

template <typename T, class P>
T& BST<T,P>::Get (const T& t)
{
  Node *  n = root_;    // travels down the tree
  Node *  p = nullptr;  // maintain as parent of n
  bool left = false;    // true iff n is left child of p 
  while(n)   // search loop
  {
    if (pred_(t,n->value_))       // t < n->value_ : go left
    {
      p = n;
      n = n->lchild_;
      left = true;
    }
    else if (pred_(n->value_,t))  // t > n->value_ : go right
    {
      p = n;
      n = n->rchild_;
      left = false;
    }
    else                          // t == n->value_ : success!
      return n->value_;  //  return by reference - tree not modified
  }
  // Search not successful
  // now p points to the last node in the search path 
  // and "left" tells us which direction we took from p to n == null
  ...

| | Top of Page | 12. Binary Search Trees - 10 of 27