二叉树获取所有左/右节点

时间:2020-01-05 09:33:16

标签: php mysql binary-tree binary-search-tree

这是我的数据库结构

id | parent_id | depth | position
---------------------------------
2  | 1         | 1     | left
---------------------------------
3  | 1         | 1     | right
---------------------------------
4  | 2         | 2     | left
---------------------------------
5  | 3         | 2     | left
---------------------------------
6  | 2         | 3     | right
---------------------------------
7  | 4         | 4     | right
---------------------------------

我编写了一个递归函数来获取特定深度上特定“ id”的总左或右节点,但是它太重了,因为深度可以达到300 +。

例如,我想获取id 2左侧部分中有多少个子节点,在这种情况下,节点2的左侧部分中有2、4和7,而在特定深度4上,节点2上只有1个子节点。左部分。

是否有更好的方法来获取特定深度上的所有左节节点计数。

protected function rec($parent_id, $current_level, $requested_level, $created_at) {

        $query = DB::select("select username, id, depth, DATE(created_at) as created_at from users where parent_id = $parent_id");

        if ($current_level == $requested_level) {                                    
            $this->result1++;
            return;
        }        
        else {
            if(!empty($query)){
                foreach($query as $row){
                    $this->rec($row->id, $row->depth, $requested_level, $row->created_at);                     
                }
            }
            else{                
                return;
            }                    
        }
    }

0 个答案:

没有答案
相关问题