使用php mysql在二叉树中查找插入位置和子节点数

时间:2015-03-16 10:04:40

标签: 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              |
+-------------+-----------+----------------+
Which represents the following tree
                      1
                      |
                  ---------
                  |       |
                  2       3
                  |
               -------
               |     |  
               4     5
               |
             -----
             |
             6

我需要找到父ID

插入的位置

例如:

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

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

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

1 - 5
2 - 3
3 - 0
4 - 1
5 - 0

我需要在php和mysql中完成这个。

有人能告诉我最简单的方法吗?

1 个答案:

答案 0 :(得分:0)

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

查找节点位置