Last active
July 11, 2017 14:45
-
-
Save midorikocak/2db194ad463a39407a216aac8898893b to your computer and use it in GitHub Desktop.
find Max on a PHP Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function createRangeArray(int $max) | |
{ | |
if ($max < 0 || $max > PHP_INT_MAX) { | |
throw new InvalidArgumentException('You bastard!'); | |
} | |
$result = []; | |
for ($i = 0; $i < $max; $i++) { | |
$result[$i] = $i; | |
} | |
return $result; | |
} | |
class TreeNode | |
{ | |
/** | |
* @var int | |
*/ | |
public $data; | |
public $max; | |
/** | |
* @var TreeNode[] | |
*/ | |
private $children; | |
public function __construct(int $data) | |
{ | |
$this->data = $data; | |
$this->children = []; | |
$this->max = $data; | |
} | |
public function addChildrenNode(TreeNode &$node) | |
{ | |
array_push($this->children, $node); | |
if ($node->max > $this->max) { | |
$this->max = $node->max; | |
} | |
} | |
public function addChildren(int $data) | |
{ | |
$node = new TreeNode($data); | |
$this->addChildrenNode($node); | |
if ($data > $this->max) { | |
$this->max = $data; | |
} | |
} | |
public static function findMax(TreeNode $root) | |
{ | |
$max = PHP_INT_MIN; | |
$queue = [$root]; | |
while (!empty($queue)) { | |
$node = array_shift($queue); | |
if ($node->data > $max) { | |
$max = $node->data; | |
} | |
if (!empty($node->children)) { | |
$queue = array_merge($queue, $node->children); | |
} | |
} | |
return $max; | |
} | |
} | |
$root = new TreeNode(1); | |
$root->addChildren(2); | |
$node = new TreeNode(2); | |
$root->addChildrenNode($node); | |
$node->addChildren(4); | |
$node->addChildren(5); | |
$node->addChildren(8); | |
$root->addChildren(7); | |
//var_dump($root); | |
echo TreeNode::findMax($root); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment