3v4l.org

run code in 300+ PHP versions simultaneously
<?php /* 构造如下一棵树: a / | \ b c d / \ | e f g | h 深度优先遍历(DFT): a b e f h c d g 广度优先遍历(BFT): a b c d e f g h */ $h = new TreeNode('h'); $g = new TreeNode('g'); $f = new TreeNode('f', [$h]); $e = new TreeNode('e'); $d = new TreeNode('d', [$g]); $c = new TreeNode('c'); $b = new TreeNode('b', [$e, $f]); $a = new TreeNode('a', [$b, $c, $d]); $tree = &$a; dft($tree); echo "\n----\n"; bft($tree); exit(); class TreeNode { public $data; public $children = []; public function __construct($data, $children = []) { $this->data = $data; $this->children = array_merge($this->children, $children); } } /** * depth first traversal * * 借助栈实现 */ function dft($tree) { $stack = array($tree, "\n"); while (!empty($stack)) { $node = array_pop($stack); if (is_string($node)) { echo $node; } else { echo $node->data; if ($node->children) { array_push($stack, "\n"); $children = array_reverse($node->children); foreach ($children as $c) { array_push($stack, "\t"); array_push($stack, $c); } array_push($stack, "\n"); } } } } /** * breadth first traversal * * 借助队列实现 */ function bft($tree) { $queue = array($tree, "\n"); while(!empty($queue)) { $node = array_shift($queue); if (is_string($node)) { echo $node; } else { echo $node->data; if ($node->children) { foreach ($node->children as $c) { array_push($queue, $c); array_push($queue, "\t"); } array_push($queue, "\n"); } } } }
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.7
a b e f h c d g ---- a b c d e f g h

preferences:
152.28 ms | 404 KiB | 188 Q