问题:有一个多叉树,如下所示:
class node {
public $data = null;
public $children = null;
public function __construct($data) {
$this->data = $data;
}
}
$root = new node(1);
$child = new node(2);
$nodeChd = new node(21);
$nodeChd1 = new node(22);
$nodeChd2 = new node(23);
$child->children[]= $nodeChd;
$child->children[]= $nodeChd1;
$child->children[]= $nodeChd2;
$root->children[] = $child;
$child = new node(3);
$nodeChd = new node(31);
$nodeChd1 = new node(32);
$nodeChd2 = new node(33);
$child->children[]= $nodeChd;
$child->children[]= $nodeChd1;
$child->children[]= $nodeChd2;
$root->children[] = $child;
$child = new node(4);
$root->children[] = $child;
$child = new node(5);
$root->children[] = $child;
$child = new node(6);
$root->children[] = $child;
要求获取从某指定叶子结点到根结点的路径,使用PHP语言实现。
实现过程如下所示:
function traverseValue($node, $parentPath, $targetValue, &$path, &$flag = false) {
if (empty($node)) {
return;
}
if ($flag == true) {
return;
}
$temp = $parentPath;
array_unshift($temp, $node->data);
$path[$node->data] = $temp;
if ($targetValue == $node->data) {
$flag = true;
return;
}
if (empty($node->children)) {
return;
}
foreach ($node->children as $valChildren) {
traverseValue($valChildren, $temp, $targetValue,$path, $flag);
}
}
$pathValue = [];
$parentPath = [];
$targetValue = 22;
$flag = false;
traverseValue($root, $parentPath, $targetValue,$pathValue, $flag);
echo "<pre>";
var_dump($pathValue[$targetValue]);
运行结果如下所示:
array(3) {
[0]=>
int(22)
[1]=>
int(2)
[2]=>
int(1)
}