public static function findSuccessor(BinaryTreeNodeWithParent $node) { $right = $node->getRight(); if ($right !== null) { return self::diveDownAndLeft($right); } $rightMostParent = self::climbUpAndRight($node); // The parent of rightMostParent must be a left parent or null // because we climbed as far right as possible return $rightMostParent->getParent(); }
public function getRandomNode() { $left = parent::getLeft(); $right = parent::getRight(); $leftNodeCount = $left !== null ? $left->getNodeCount() : 0; $rightNodeCount = $right !== null ? $right->getNodeCount() : 0; $random = mt_rand(-$leftNodeCount, $rightNodeCount); if ($random < 0) { return $left->getRandomNode(); } elseif ($random > 0) { return $right->getRandomNode(); } // $random == 0 return $this; }