3v4l.org

run code in 300+ PHP versions simultaneously
<?php $a= array ( 1 => 0, 2 => 1, 3 => 2, 4 => 3, 5 => 1, 6 => 0 ); class node { var $children; public function __construct(){ $this->children = array(); } } $tree = array(); foreach ($a as $q => $p){ if(!isset($tree[$p])) $tree[$p] = new node; if(!isset($tree[$q])) $tree[$q] = new node; $mark[$p]=FALSE; $mark[$q]=FALSE; array_push($tree[$p]->children,$q); } function dfs(&$ans,$node){ global $tree, $mark; $mark[$node] = TRUE; $ans = array(); foreach($tree[$node]->children as $child) if(!$mark[$child]){ $ans[$child]=$child; dfs($ans[$child],$child); } } $parent=1; dfs($ans,$parent); echo($ans); ?>

preferences:
40.85 ms | 402 KiB | 5 Q