Example #1
0
 /**
  * Finds an object in this M-way tree that matches
  * the specified object.
  * Uses linear search.
  *
  * @param object IComparable $obj The object to match.
  * @return mixed An object that matches the specified one;
  * NULL if the tree is empty.
  */
 public function find(IComparable $obj)
 {
     if ($this->isEmpty()) {
         return NULL;
     }
     for ($i = $this->count; $i > 0; --$i) {
         $diff = $obj->compare($this->key[$i]);
         if ($diff == 0) {
             return $this->key[$i];
         }
         if ($diff > 0) {
             break;
         }
     }
     return $this->subtree[$i]->find($obj);
 }
Example #2
0
 /**
  * Withdraws the specified object from this binary search tree.
  *
  * @param object IObject $obj The object to be withdrawn from this tree.
  */
 public function withdraw(IComparable $obj)
 {
     if ($this->isEmpty()) {
         throw new ArgumentError();
     }
     $diff = $obj->compare($this->getKey());
     if ($diff == 0) {
         if (!$this->getLeft()->isEmpty()) {
             $max = $this->getLeft()->findMax();
             $this->key = $max;
             $this->getLeft()->withdraw($max);
         } elseif (!$this->getRight()->isEmpty()) {
             $min = $this->getRight()->findMin();
             $this->key = $min;
             $this->getRight()->withdraw($min);
         } else {
             $this->detachKey();
         }
     } else {
         if ($diff < 0) {
             $this->getLeft()->withdraw($obj);
         } else {
             $this->getRight()->withdraw($obj);
         }
     }
     $this->balance();
 }