我有这样的树:
每个节点都是一个数组,节点类型是它的第一个元素,其他元素是节点的参数(它们可以是其他节点的列表、单个节点、某些值等;节点可以没有参数、一个参数或多个参数)。
你认为遍历这种类型的树最优雅的方式是什么?
我想到了两种可能性:
1)使用 switch 语句。
$tree = array("A", array(
array("B", 1),
array("C", 2),
array("D",
array("E",
array("F")),
array("G")),
array("H", 3)));
每个节点都是一个数组,节点类型是它的第一个元素,其他元素是节点的参数(它们可以是其他节点的列表、单个节点、某些值等;节点可以没有参数、一个参数或多个参数)。
你认为遍历这种类型的树最优雅的方式是什么?
我想到了两种可能性:
1)使用 switch 语句。
/*
* + shorter
* + fall-througs (easy way to handle more nodes with same code)
*
* - worse readability
*/
function my_tree_walker($tree)
{
switch ($tree[0]) {
case 'A':
list($_, $subnodes) = $tree;
$ret = '';
foreach ($subnodes as $subnode) {
$ret .= my_tree_walker($subnode);
}
return $ret;
break;
case 'B': /*...*/ break;
case 'C': /*...*/ break;
case 'D': /*...*/ break;
case 'E': /*...*/ break;
case 'F': /*...*/ break;
case 'G': /*...*/ break;
case 'H': /*...*/ break;
}
}
2) 每种节点类型都有对应方法的对象
/*
* + better readability
* + more declarative
*
* - longer
* - `new static` is PHP >=5.3 only
*/
abstract class TreeWalker
{
protected function __construct(){}
final protected function walk($node)
{
$nodetype = array_shift($node);
return call_user_func_array(array($this, 'walk' . $nodetype), $node);
}
public static function w($tree)
{
$instance = new static;
return $instance->walk($tree);
}
}
final class MyTreeWalker extends TreeWalker
{
protected function __construct()
{
// initialize
}
private function walkA($subnodes)
{
$ret = '';
foreach ($subnodes as $subnode) {
$ret .= $this->walk($subnode);
}
return $ret;
}
private function walkB($n) { /*...*/ }
private function walkC($n) { /*...*/ }
private function walkD($subnode) { /*...*/ }
private function walkE() { /*...*/ }
private function walkF() { /*...*/ }
private function walkG() { /*...*/ }
private function walkH($n) { /*...*/ }
}
你是否建议更加优雅的遍历树的方式?
我也考虑过将节点作为对象,而不是使用单独的树遍历器,每个节点都有用于内部遍历的方法。然而,我认为这会使代码更难维护,因为遍历器的部分代码将被放置在不同的位置,并且更难将同一代码用于多个节点。