在某些情况下,我不得不计算二叉树的左子和右子,我的数据库结构如下所示。
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;如果您没有解决方案,请不要标记重复或任何其他
发布于 2014-12-05 14:21:08
您需要使用这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); // 13https://stackoverflow.com/questions/27314676
复制相似问题