Tree traversal

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
$dfs = function ($tree) use (&$dfs) {
$name = $tree[0];
$children = $tree[1] ?? null;
echo "$name \n";
if (!$children) {
return;
}
return array_map($dfs, $children);
};
$tree = ['A', [
['B', [['E'], ['F']]],
['C'],
['D', [['G'], ['J']]],
]];
$dfs($tree);
// => A
// => B
// => E
// => F
// => C
// => D
// => G
// => J