簡體   English   中英

如何從二叉樹數據庫中計算左孩子或右孩子的數量

[英]how to count no of left or right child from binary tree database

這是我桌子的假人

桌子

  • 第一個節點是 1
  • LorR 定義孩子是 ini left(0) 或 Right(1)
  • 第一個節點在 Left 和 Right 中有兩個子節點 2 和 3
  • 第二個節點在 Left 和 Right 中有兩個子節點 4 和 5
  • 第 3 個節點在 Left 和 Right 中有兩個子節點 6 和 7
  • 第 4 個節點在 Left 和 Right 中有兩個子節點 8 和 9
  • 第 5 個節點在左側有一個子節點 10
  • 第 6 個節點在左側有一個子節點 11
  • 第 7 個節點在 Right 有一個子節點 12

現在,如果我想查找每個級別中任何父節點的總子節點數,例如...

  • 節點 2(父節點)在級別 1 中具有 2 個子節點(4,5),在級別 2 中具有 2 個子節點(8,9)
  • 節點 6(父節點)在級別 1 中有 1 個子節點 (11)
  • 節點 3(父節點)在級別 1 中具有 2 個子節點(6,7),在級別 2 中具有 2 個子節點(11,12)

我如何使用 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

然后你應該刪除最后一個元素 - 它沒有用,因為它被用來按級別計算孩子。

筆記:

  1. 它應該有更好的方法來組織數據(數組 $a),以便更輕松地實現 getChildrenCount()。
  2. 這段代碼沒有仔細測試,只是檢查了一些情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM