二进制树,如何计算所有左右儿童php,mysql

时间:2018-05-25 09:55:28

标签: php mysql

Table name classes I show you database screenshot

我正在尝试此代码,但输出为0 亲爱的朋友,我必须计算二叉树的左子和右子我的数据库结构如下。

 function allcount($id)
{
    $sql = "SELECT parentsclass, childclassleft, childclassright FROM classes WHERE parentsclass = '".$id."'";
    $execsql = mysqli_query($conn,$sql); 
    $array = mysqli_fetch_array($execsql);  
    (array_count_values($array)); 
    $count = 0;  
    if(!empty($array['childclassleft']))
    {
        $count += allcount($array['childclassleft']) +1;
    }
    if(!empty($array['childclassright'])) 
    {
        $count += allcount($array['childclassright']) +1;
    }
    return $count; 
}

echo allcount();

1 个答案:

答案 0 :(得分:0)

我使用此代码此代码计算左右子节点....

$memid="95000";   // your id

function getTotalLeg($memid,$leg){ 
      global $conn;
     $sql="select child_class from tree_class where parent_id='".$memid."' and position='".$leg."'";
      $res=mysqli_query($conn,$sql);
      $row=mysqli_fetch_array($res);
      global $total;
       $total=$total+mysqli_num_rows($res);
         if($row['child_class']!=''){
           getTotalLeg ($row['child_class'],'L');
           getTotalLeg ($row['child_class'],'R');
          } 
          return $total;      
        }      

     $total=0; 
    $left=getTotalLeg($memid,"L");    
    echo $total."</br>"; 
     $total=0;
    $right=getTotalLeg($memid,"R");  
    echo $total;