gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 06:52:22 25 4
gpt4 key购买 nike

下面是我的表格数据

+-------------+-----------+----------------+| 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

我需要通过parent id找到插入的位置

例如:

1) 如果parent id是1那么insert位置就是root-3 position-L
2) 如果 parent_id 是 2 那么插入位置将是 root-4 position-R
3) 如果 parent_id 是 3 那么插入位置将是 root-3 position-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 查找节点位置按预期工作

关于php - 使用php mysql在二叉树中查找插入位置和子节点数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29074065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com