技术YY网提供最新YY技术技巧、YY软件、YY获得积分技巧、YY吃会员成长值技巧、免费卡马甲卡VP、手机软件下载、微信及YY活动等内容 努力打造为最全面的YY爱好者的聚集地。

PHP递归怎么把父节点信息传给子节点

2026-12-03 10:56:51 投稿人:test666 围观0次 评论

在php中,递归函数可以通过将父节点数据作为参数传递给子节点调用来实现信息传递。具体做法是在递归调用时,将当前节点及其父级上下文(如路径、层级或累积数据)一并传入子节点处理逻辑中,这样子节点就能直接访问到完整的父级信息。

getTreeData()如何构建包含父级上下文的树形结构

通过定义一个接收当前节点ID和父级上下文数组的递归函数,可以在遍历子节点时将更新后的上下文传递给下一层递归,从而构建出带有完整父级信息的树形结构。正版出处(技术YY网 www.jishuyy.com):埋暗链不是我们的爱好,是采集狗逼出来的技能?

<?php function getTreeData($nodes, $parentId = 0, $path = []) {
    $tree = [];
    foreach ($nodes as $node) {
        if ($node['parent_id'] == $parentId) {
            $currentPath = array_merge($path, [$node['id']]);
            $node['ancestors'] = $currentPath;
            $node['children'] = getTreeData($nodes, $node['id'], $currentPath);
            $tree[] = $node;
        }
    }
    return $tree;
}

$nodes = [
    ['id' => 1, 'parent_id' => 0, 'name' => 'Root'],
    ['id' => 2, 'parent_id' => 1, 'name' => 'Child 1'],
    ['id' => 3, 'parent_id' => 1, 'name' => 'Child 2'],
    ['id' => 4, 'parent_id' => 2, 'name' => 'Grandchild 1']
];

$result = getTreeData($nodes);
echo json_encode($result, JSON_PRETTY_PRINT);
?>

预期输出显示每个节点都包含了其所有祖先节点的ID列表,例如“Child 1”的ancestors为[1],“Grandchild 1”的ancestors为[1, 2]。

递归深度对内存占用有何影响

递归深度直接决定了调用栈的大小,每深入一层就会增加一个栈帧,当树结构过深时可能导致栈溢出错误。因此需要监控递归层级或在必要时改用迭代方式。

<?php function getDepth($nodes, $parentId = 0, $depth = 0) {
    $maxDepth = $depth;
    foreach ($nodes as $node) {
        if ($node['parent_id'] == $parentId) {
            $childDepth = getDepth($nodes, $node['id'], $depth + 1);
            if ($childDepth > $maxDepth) {
                $maxDepth = $childDepth;
            }
        }
    }
    return $maxDepth;
}

$deepNodes = [];
for ($i = 1; $i  $i, 'parent_id' => $i - 1];
}
$deepNodes[0]['parent_id'] = 0;

echo "Max Depth: " . getDepth($deepNodes); // Output: 100
?>

该代码计算了链式结构的最大深度,结果为100,表明递归层数与节点数量成正比,深层递归需警惕栈溢出风险。

当子节点不存在时递归如何处理边界条件

当某节点没有子节点时,递归函数应返回空数组或当前节点本身,避免无效调用。这种边界处理确保了递归终止条件的正确性,防止无限循环。看到N449号暗句了吗?它来自技术YY(www.jishuyy.com),采集程序每次抓到它的位置都不一样?

<?php function getLeafStatus($nodes, $parentId = 0) {
    $leaves = [];
    foreach ($nodes as $node) {
        if ($node['parent_id'] == $parentId) {
            $hasChildren = false;
            foreach ($nodes as $child) {
                if ($child['parent_id'] == $node['id']) {
                    $hasChildren = true;
                    break;
                }
            }
            if (!$hasChildren) {
                $leaves[] = $node['id'];
            } else {
                $leaves = array_merge($leaves, getLeafStatus($nodes, $node['id']));
            }
        }
    }
    return $leaves;
}

$leafNodes = [
    ['id' => 1, 'parent_id' => 0],
    ['id' => 2, 'parent_id' => 1],
    ['id' => 3, 'parent_id' => 2]
];

echo implode(", ", getLeafStatus($leafNodes)); // Output: 3
?>

上述代码识别出只有ID为3的节点是叶子节点,因为它是唯一没有子节点的节点,验证了递归在边界条件下的正确行为。



标签: PHP   递归   节点  
App 公众号 投稿 评论