使用 php mysql 查找二叉树中的插入位置和子项数量


Find insert position and number of childs in a binary tree using php mysql

下面是我的表数据

+-------------+-----------+----------------+|customer_id |parent_id |node_direction |+-------------+-----------+----------------+|          1 |        0 |T ||          2 |        1 |L ||          3 |        1 |R ||          4 |        2 |L ||          5 |        2 |R ||          6 |        4 |L |+-------------+-----------+----------------+代表以下树                      1                      |                  ---------                  |      |                  2       3                  |               -------               |    |                4     5               |             -----             |             6

我需要通过父 ID 找到插入的位置

例如:

1) 如果父 ID 为 1,则插入位置将是根-3 位置-L
2) 如果parent_id为 2,则插入位置将为根-4 位置-R
3) 如果parent_id为 3,则插入位置将为根-3 位置-L

问题是它需要遵循二进制结构

我还需要按父节点计算子节点,例如:

1 - 52 - 33 - 04 - 15 - 0

我需要在php和mysql中完成此操作。

谁能向我建议最简单的方法来实现这一目标?

function getNodeInsertPostionByParentId($parentId){
        $position = array('status'=>false);
        $parents = array();
        foreach($parentId as $parent){              
                $qry = "select customer_id,node_direction from mlm_nodes where parent_id =".$parent." order by node_direction";
                $rst = mysql_query($qry);
                $count = mysql_num_rows($rst);
                if($count==2){
                    while($row = mysql_fetch_assoc($rst)){
                        $parents[$parent][] = $row['customer_id'];
                    }   
                }elseif($count==1){
                    $position['status'] = true;
                    $position['parentId'] = $parent;
                    $position['node'] = 'R';
                    //echo '<pre>1';print_r($position);echo '</pre>';
                    return $position;
                }else{
                    $position['status'] = true;
                    $position['parentId'] = $parent;
                    $position['node'] = 'L';
                    //echo '<pre>2';print_r($position);echo '</pre>';
                    return $position;
                }
            }
        return $this->searchByParents($parents);
    }
    function searchByParents($parents){
        foreach($parents as $parent){
            return $this->getNodeInsertPostionByParentId($parent);  
        }
    } 

echo '<pre>';print_r($this->getNodeInsertPostionByParentId(array('4')));die;

这符合预期的方式通过父 ID 查找节点位置