gpt4 book ai didi

php - 如何定义构建二叉树的递归函数的深度级别?

转载 作者:行者123 更新时间:2023-11-28 23:30:10 25 4
gpt4 key购买 nike

我在 mysql 数据库中有一个 persons 表,每个人都有母亲和父亲,所以我需要构建继承树并且我有一个函数,如果只是运行它,它工作正常,但我需要定义继承树的深度,我为此制作了引用变量,它很好地计算了递归但还有另一个问题,它只为母线制作树,如果我切换'if'语句它将只构建父树,我该如何制作它工作还是有其他方法?

public function makeTree(array &$rootPerson, &$quantity = 14)
{
if ($quantity < 0) {
return;
}

if (isset($rootPerson['mother_id'])) {
$rootPerson['parents']['mother'] = $this->getPerson($rootPerson['mother_id']);
$this->makeTree($rootPerson['parents']['mother'], --$quantity);
}

if (isset($rootPerson['father_id'])) {
$rootPerson['parents']['father'] = $this->getPerson($rootPerson['father_id']);
$this->makeTree($rootPerson['parents']['father'], --$quantity);
}
}

最佳答案

递归跟随第一部分一直向下到 $quantity === -1 然后 $quantity 将是相同的值,无论什么级别 因为您是通过引用这样做的。如果您更改它以便每次迭代都有自己的版本并且您只在到达那里后才减少它:

public function makeTree(array &$rootPerson, $quantity = 14)
{
if ($quantity < 0) {
return;
}

$quantity--;

if (isset($rootPerson['mother_id'])) {
$rootPerson['parents']['mother'] = $this->getPerson($rootPerson['mother_id']);
$this->makeTree($rootPerson['parents']['mother'], $quantity);
}

if (isset($rootPerson['father_id'])) {
$rootPerson['parents']['father'] = $this->getPerson($rootPerson['father_id']);
$this->makeTree($rootPerson['parents']['father'], $quantity);
}
}

关于php - 如何定义构建二叉树的递归函数的深度级别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37618409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com