| | | | | |

Table::Get

Same logic as Set::Get - use key for decisions and data to read/write

  D& Get (const KeyType& k)
  {
    if (root_ == nullptr)
    {
      root_ = NewNode(k,D());
      return root_->data_;
    }
    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 != nullptr)   // search loop
    {
      if (pred_(k,n->key_))       // k < n->key_ : go left
      {
        p = n;
        n = n->lchild_;
        left = true;
      }
      else if (pred_(n->key_,k))  // k > n->key_ : go right
      {
        p = n;
        n = n->rchild_;
        left = false;
      }
      else                        // key found
      {
        n->SetAlive();
        return n->data_;  //  return by reference - tree not modified
      }
    }
    // if we arrive here, search has failed
    // p points to the last node in the search path
    // "left" tells us which direction we took from p to n == nullptr
    n = NewNode(k,D());                        // create new node with key k
    (left ? p->lchild_ = n : p->rchild_ = n);  // attach n to left or right of p
    return n->data_;                           // return by reference - see
  }

| | Top of Page | 12. Binary Search Trees - 38 of 41