2014-12-05 89 views
1

我被困在一些情況下,我必須計算二進制樹的左孩子和右孩子我的數據庫結構如下。二進制樹兒童計數php mysql

SELECT id,usr_name,rid,pid,l_mem,r_mem,position,joining_date FROM user WHERE id = '$id'" 

其中RID是=轉診ID和PID =父ID,

我需要算定父ID的所有葉例如

如果ID 1已經離開2,右3個即時孩子的我需要知道左總成員數和總成員數。

          1 
            / \ 
            2  3 
            /\ /\ 
            4 5 6 7 
           / \  \ 
           8   9  11 
          /     \ 
          10      12 
         /\ 
         13 14 

我需要統計的1 所有孩子的我使用這個功能,但只計算最左邊,請修改,或解釋自己

function leftcount($id) //Function to calculate leftcount 
    { 
    $sql = "SELECT id,usr_name,rid,pid,l_mem,r_mem,position,joining_date FROM user WHERE id = '$id'"; 
    $execsql = mysql_query($sql); 
    $array = mysql_fetch_array($execsql); 
    //var_dump($array); 
    (array_count_values($array)); 
    if(!empty($array['l_mem'])) 
    { 
     $count += leftcount($array['l_mem']); 
    } 


    $totalcount = 1 + $count; 
    return $totalcount ; 

    } 

     $left = leftcount($id); 
     doing -1 because in function 1 + $count. 
     $left = $left-1; 

請不要標記複製或任何其他如果你沒有解決方案

回答

-1

您需要使用這3個函數來計算任何元素的左側右側和所有孩子。

function leftcount($id) //Function to calculate all left children count 
{ 
    $sql = "SELECT id,usr_name,rid,pid,l_mem,r_mem,position,joining_date FROM user WHERE id = '$id'"; 
    $execsql = mysql_query($sql); 
    $array = mysql_fetch_array($execsql); 
    (array_count_values($array)); 
    $count = 0; 
    if(!empty($array['l_mem'])) 
    { 
     $count += allcount($array['l_mem']) +1; 
    } 
    return $count; 
} 
function rightcount($id) //Function to calculate all right children count 
{ 
    $sql = "SELECT id,usr_name,rid,pid,l_mem,r_mem,position,joining_date FROM user WHERE id = '$id'"; 
    $execsql = mysql_query($sql); 
    $array = mysql_fetch_array($execsql); 
    (array_count_values($array)); 
    $count = 0; 
    if(!empty($array['r_mem'])) 
    { 
     $count += allcount($array['r_mem']) +1; 
    } 
    return $count; 
} 
function allcount($id) //Function to calculate all children count 
{ 
    $sql = "SELECT id,usr_name,rid,pid,l_mem,r_mem,position,joining_date FROM user WHERE id = '$id'"; 
    $execsql = mysql_query($sql); 
    $array = mysql_fetch_array($execsql); 
    (array_count_values($array)); 
    $count = 0; 
    if(!empty($array['l_mem'])) 
    { 
     $count += allcount($array['l_mem']) +1; 
    } 
    if(!empty($array['r_mem'])) 
    { 
     $count += allcount($array['r_mem']) +1; 
    } 
    return $count; 
} 

如果您將1傳遞給這些函數。回答這些如下

echo leftcount(1); // 8 
echo rightcount(1); // 5 
echo allcount(1); // 13 
+0

嗨阿肖克謝謝你的回答,但出了問題! 左右計數不起作用。 – 2014-12-10 23:38:32

+0

Allcount工作正常嗎?因爲所有其他功能都依賴於它。 – 2014-12-11 05:26:00

+0

是的allcount工作正常。 – 2014-12-12 08:48:16