Skip to content

Instantly share code, notes, and snippets.

@ViKingIX
Last active February 22, 2017 08:09
Show Gist options
  • Save ViKingIX/ad4cf112992c7fa5038fdc29ad7c2e55 to your computer and use it in GitHub Desktop.
Save ViKingIX/ad4cf112992c7fa5038fdc29ad7c2e55 to your computer and use it in GitHub Desktop.
build tree bottom up then traverse top down
<?php
class Node {
public $val;
public $mem;
public $par;
function __constructor($v)
{
$this->val = $v;
$this->mem = Array();
$this->par = Array();
}
}
function main()
{
$real_roots = build(102);
foreach ($real_roots as $root)
traverse($root);
}
function build($x)
{
$node = new Node($x);
$real_roots = [];
build_body($node, $real_roots);
return $real_roots;
}
function build_body($node, &$real_roots)
{
$temp_parents = find_parents($node);
foreach ($temp_parents as $i)
{
$p = new Node($i);
array_push($p->mem, $node);
array_push($node->par, $p);
build_body($p, $real_roots);
}
if (empty($temp_parents))
array_push($real_roots, $node);
return;
}
function traverse($node)
{
// do something
foreach ($node->mem as $mem)
traverse($mem);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment