【问题标题】:Get binary tree elements count at n-th depth using PHP使用 PHP 获取第 n 个深度的二叉树元素计数
【发布时间】:2020-05-15 12:52:54
【问题描述】:

我有代表二进制结构的users 表。

例如,userleft_idright_id 可以是二进制的左右节点(left_idright_idusers 表的外键)。

此外,user 具有 parent_id,它是 user 元素的上述(根)节点。

我需要计算一侧(左侧或右侧)从根的第 n 个深度处的二进制元素计数。

例如,看下面的图片。 用户左侧有 2 个深度的 3 个元素,左侧有 3 个深度的 7 个元素

For example, the user has 3 elements at 2-depth for left side, and it has 7 elements at 3-th depth for the left side

我正在为应用程序使用 Laravel 框架并尝试解决问题: 我有一个计算用户元素的递归函数。

    private function followersCount($depth, &$step)
    {
        $sum = 0;
        // children attribute is the array of left and right elements
        foreach ($this->children as $child) {
            if ($step == $depth) return $sum; 
            $sum += $sum + $child->followersCount($depth, $step);
        }
        $step++;

        return $this->children->count() + $sum;
    }

但它会迭代所有二进制元素,无法控制$step 变量。 如果您有任何解决方案,我将不胜感激。

【问题讨论】:

    标签: php laravel binary-tree


    【解决方案1】:

    我要调整的东西:

    • 不需要通过引用发送步进变量。
    • 您的$step++ 在循环之后,导致下一个递归步骤的错误值
    • 当您使用$sum += $sum 时,您的递归总和翻了一番
        private function followersCount($depth, $step)
        {
            $sum = 0;
    
            // children attribute is the array of left and right elements
            if ($step <= $depth) {
                $step++;
                foreach ($this->children as $child) {
                    $sum += $child->followersCount($depth, $step);
                }
            }
    
            return $this->children->count() + $sum;
        }
    

    【讨论】:

    • 感谢您的回答。我已经按照您的建议修改了我的代码,但没有帮助。我作为参数传递$this-&gt;followersCount(3, 1),它返回 30,但它应该返回 7。不明白为什么。
    • 尝试调试你的树,也许你比你想象的要低一步。也许
    猜你喜欢
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2010-12-24
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    相关资源
    最近更新 更多