Php 用改进的前序树遍历算法溢出二叉树中的新节点
我想用php在MlM应用程序中实现二叉树布局 使用的术语: 推荐人,上线,下线 一个推荐人只会是前两个推荐人的上线,其他推荐人会从左到右溢出到二叉树以填充任何可用空间 例如:Php 用改进的前序树遍历算法溢出二叉树中的新节点,php,binary-tree,Php,Binary Tree,我想用php在MlM应用程序中实现二叉树布局 使用的术语: 推荐人,上线,下线 一个推荐人只会是前两个推荐人的上线,其他推荐人会从左到右溢出到二叉树以填充任何可用空间 例如: “A”指“B”、“C”和“D” “B”和“C”,并作为“A”的下线放置 然后将“C”溢出到下一个可用空间 在这种情况下,在“B”的左侧,因为还没有任何下线 A /\ / \ B C / D 假设每个推荐人只带来2个人,我可以使用改进的前序树遍历算法自动将其添加到表中 但我的挑战是确定表上的下一个可用空间
A
/\
/ \
B C
/
D但我的挑战是确定表上的下一个可用空间(顺序),以添加已经有2条下线的推荐人的溢出。我终于自己解决了这个问题
//traverse the network binary tree to fetch the next available upline to place the user under
function get_next_free_upline($pref, $sponsor_id)
{
$ref_id = $sponsor_id;
$get_next = TRUE;
$level = 1;
$lft = $this->get_pointers($ref_id, 'lft');
$rgt = $this->get_pointers($ref_id, 'rgt');
$offset = $this->get_offset($lft, $rgt);
while ($get_next !== FALSE)
{
$query = $this->db->query
(' SELECT node.*, (COUNT(parent.upline_id) - ' . $offset . ') AS level
FROM tree AS node
CROSS JOIN tree AS parent
WHERE (node.lft BETWEEN parent.lft AND parent.rgt AND
node.lft > ' . $lft .' AND node.rgt < ' . $rgt . ')
GROUP BY node.id
having level = ' . $level . '
ORDER BY node.lft
');
$result = $query->result();
//check if this upline has less than 2 downlines
//if yes, assign the user_id to upline and return
if ($query->num_rows() < 2)
{
$upline_id = $sponsor_id;
$get_next = FALSE;
}
else
{ //loop through all members under the current sponsor id
//to know where to spill over the referred member
foreach ($result as $row):
$sponsor_id = $row->id;
//check all occurences of this level member as an upline
$this->db->select('*');
$this->db->from('tree');
$this->db->where('upline_id', $sponsor_id);
$inner_query = $this->db->get();
if ($inner_query->num_rows() < 2)
{
$upline_id = $sponsor_id;
$get_next = FALSE;
break;
}
endforeach;
//increase the level number and loop back
$level = $level + 1;
$get_next = TRUE;
}
}
return $upline_id;
}
//遍历网络二叉树以获取下一个可用的上线,将用户置于其下
函数get\u next\u free\u上线($pref,$赞助商\u id)
{
$ref_id=$赞助商_id;
$get_next=TRUE;
$level=1;
$lft=$this->get_指针($ref_id,'lft');
$rgt=$this->get_指针($ref_id,'rgt');
$offset=$this->get_offset($lft,$rgt);
while($get_next!==FALSE)
{
$query=$this->db->query
('SELECT node.*,(COUNT(parent.upline_id)-'.$offset.')作为级别
从树作为节点
作为父级的交叉连接树
其中(parent.lft和parent.rgt之间的node.lft和
node.lft>“.$lft.”和node.rgt<”.$rgt.)
按node.id分组
具有级别='.$level'
按节点排序。lft
');
$result=$query->result();
//检查该上行线是否少于2条下行线
//如果是,将用户id分配给上线并返回
如果($query->num\u rows()<2)
{
$upline\u id=$赞助商\u id;
$get_next=FALSE;
}
其他的
{//循环浏览当前赞助商id下的所有成员
//知道在何处溢出被推荐的成员
foreach($结果为$行):
$sandor\u id=$row->id;
//作为上线检查此级别成员的所有事件
$this->db->select('*');
$this->db->from('tree');
$this->db->where('upline\u id',$sandor\u id);
$internal_query=$this->db->get();
if($inner\u query->num\u rows()<2)
{
$upline\u id=$赞助商\u id;
$get_next=FALSE;
打破
}
endforeach;
//增加关卡编号并返回
$level=$level+1;
$get_next=TRUE;
}
}
返回$upline\u id;
}