Skip to content

Instantly share code, notes, and snippets.

@jazzdan
Forked from anonymous/node.php
Last active February 25, 2017 22:06
Show Gist options
  • Save jazzdan/3f665f91549736416af41c15f6d68b3f to your computer and use it in GitHub Desktop.
Save jazzdan/3f665f91549736416af41c15f6d68b3f to your computer and use it in GitHub Desktop.
<?hh // strict
class Node {
private int $value;
public ?Node $left = null;
public ?Node $right = null;
public function __construct(int $value) {
$this->value = $value;
}
}
class BSTToDoublyLinkedList {
public static function convert(?Node $root): ?Node {
if ($root === null) {
return $root;
}
if ($root && $root->left !== null) {
$left = self::convert($root->left);
if ($left) {
// make left point to predecessor
while ($left->right !== null) {
$left = $left->right;
}
$left->right = $root;
$root->left = $left;
}
}
if ($root && $root->right !== null) {
$right = self::convert($root->right);
if ($right) {
// make right point to successor
while ($right->left !== null) {
$right = $right->left;
}
$right->left = $root;
$root->right = $right;
}
}
return $root;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment