Skip to content

Instantly share code, notes, and snippets.

@sich
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sich/9178007 to your computer and use it in GitHub Desktop.
Save sich/9178007 to your computer and use it in GitHub Desktop.
Perfectly balanced tree
function tree(&$tree, $num_nodes)
{
if($num_nodes == 0)
return null;
$left = (int)($num_nodes / 2);
$right = $num_nodes - $left -1;
$tree[]['value'] = (int)(mt_rand( 1, 50) / $num_nodes+1);
$last = count($tree)-1;
$tree[$last]['left'] = tree($tree, $left);
$tree[$last]['right'] = tree($tree, $right);
return $last;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment