[英]how to count no of left or right child from binary tree database
這是我桌子的假人
現在,如果我想查找每個級別中任何父節點的總子節點數,例如...
我如何使用 php 實現這個? 我的代碼是代碼
根據我的理解,您應該將表轉換為信息豐富的 PHP 數組,例如:
$a = array(
1 => array(
'children' => array(
array(2, 'left'),
array(3, 'right'),
),
'level' => 0
),
2 => array(
'children' => array(
array(4, 'left'),
array(5, 'right'),
),
'level' => 1
),
...
12 => array(
'children' => array(),
'level' => 3
),
);
這個任務很簡單,只需獲取表然后 foreach 並將每一行分配到關聯的數組中。 這是讓所有孩子計數的函數:
function getChildrenCount($nodeId, $a, $rootLevel)
{
$leftChildren = array();
$rightChildren = array();
$countCurrentNode = 0;
$level = $a[$nodeId]['level'] - $rootLevel;
if (empty($a[$nodeId]['children'])) {
return array($level => 1);
} else {
foreach ($a[$nodeId]['children'] as $children) {
if ($children[1] == 'left') {
$leftChildren = getChildrenCount($children[0], $a, $rootLevel);
$countCurrentNode++;
}
if ($children[1] == 'right') {
$rightChildren = getChildrenCount($children[0], $a, $rootLevel);
$countCurrentNode++;
}
}
$current = $leftChildren;
foreach ($rightChildren as $rightLevel => $count) {
if (isset($current[$rightLevel])) {
$current[$rightLevel] += $count;
} else {
$current[$rightLevel] = $count;
}
}
$current[$level] = $countCurrentNode;
return $current;
}
}
思想是遞歸遍歷每個節點,然后根據其級別(與根級別相比)計算子節點的數量
如何調用:
getChildrenCount(2, $a, $a[2]['level'])
它將返回數組(級別 => 計數):
array (size=3)
0 => int 2 // level 1
1 => int 3 // level 2
2 => int 3 // Should be removed
然后你應該刪除最后一個元素 - 它沒有用,因為它被用來按級別計算孩子。
筆記:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.