使用改进的遍历树遍历算法在二叉树中的新节点上溢出

问题描述 投票:1回答:2

我想使用php在MlM应用程序中实现二叉树放置,

使用的术语:

引荐来源,上线,下线

推荐人将仅是前两个推荐人的上线,其他推荐人将溢出到二叉树中,以从左到右填充任何可用空间

示例:

  1. “ A”表示“ B and” C“和” D“,
  2. “ B”和“ C”,并作为“ A”的下线放置,
  3. “ C”然后溢出到下一个可用空间。
  4. 在这种情况下,在“ B”的左侧,因为还没有任何下线

      A
      /\
     /  \
    B    C
    

    /D

[假设每个引荐来源仅带来2个人,我就可以使用修改后的预排序树遍历算法将其自动添加到表格中,

但是我的挑战是(依次)确定表上的下一个可用空间,以添加已经有2条下线的引荐来源的溢出内容。

php binary-tree
2个回答
0
投票

我终于自己解决了这个问题。

//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;
    }

0
投票

这不是与您的问题有关的答案,而是另一个问题

您还能解决这个问题吗?这是发布链接:

Implementing Spilover system in mlm binary plan to join a user on last available child on selected side

© www.soinside.com 2019 - 2024. All rights reserved.