Last active
February 22, 2017 08:09
-
-
Save ViKingIX/ad4cf112992c7fa5038fdc29ad7c2e55 to your computer and use it in GitHub Desktop.
build tree bottom up then traverse top down
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 | |
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