【问题标题】:How to define level of depth in recursion function that builds binary tree?如何在构建二叉树的递归函数中定义深度级别?
【发布时间】:2016-06-03 15:36:31
【问题描述】:

我在mysql db中有一个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);
    }
}

【问题讨论】:

    标签: php mysql recursion tree


    【解决方案1】:

    递归跟随第一部分一直到$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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-08
      • 2022-01-26
      • 2010-12-15
      • 1970-01-01
      • 2018-05-28
      • 2012-10-29
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      相关资源
      最近更新 更多