PHP code example of willvincent / splaytree

1. Go to this page and download the library: Download willvincent/splaytree library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

willvincent / splaytree example snippets


use SplayTree\SplayTree;

// Default comparator (spaceship operator)
$tree = new SplayTree();

// Custom comparator for integers
$tree = new SplayTree(function ($a, $b) {
    return $a <=> $b;
});

$tree->insert(5);
$tree->insert(3);
$tree->insert(7);

$found = $tree->search(3);
if ($found !== null) {
    echo "Found: " . $found . "\n"; // Found: 3
}

$tree->delete(3);

  $tree->insert(10);

  $result = $tree->search(10);
  echo $result !== null ? "Found: $result" : "Not found";

  $tree->delete(10);

  $min = $tree->min();
  echo $min !== null ? "Min: $min" : "Tree is empty";

  $max = $tree->max();
  echo $max !== null ? "Max: $max" : "Tree is empty";

  $next = $tree->next(5);
  echo $next !== null ? "Next: $next" : "No successor";

  $prev = $tree->prev(5);
  echo $prev !== null ? "Prev: $prev" : "No predecessor";

  $size = $tree->getSize();
  echo "Tree size: $size";

  if ($tree->isEmpty()) {
      echo "Tree is empty\n";
  }

  $tree->clear();

  if ($tree->contains(5)) {
      echo "Tree contains 5\n";
  }

  echo $tree->toString(function ($data) {
      return (string)$data;
  });

  foreach ($tree as $data) {
      echo $data . "\n";
  }

class Person {
    public $age;
    public function __construct($age) {
        $this->age = $age;
    }
}

$comparator = function ($a, $b) {
    return $a->age <=> $b->age;
};

$tree = new SplayTree($comparator);
$tree->insert(new Person(25));
$tree->insert(new Person(30));
$tree->insert(new Person(20));

$minPerson = $tree->min();
echo $minPerson->age; // 20

$tree->insert(3);
$tree->insert(5);
$tree->search(3); // Splays 3 to the root

echo $tree->getRoot(); // 3