Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

求二元樹第 K 層的節點數與葉子節點數:遞歸與非遞歸雙解

節點定義

typedef struct BTreeNodeElement_t_ {
    void *data;
} BTreeNodeElement_t;

typedef struct BTreeNode_t_ {
    BTreeNodeElement_t *m_pElemt;
    struct BTreeNode_t_  *m_pLeft;
    struct BTreeNode_t_  *m_pRight;
} BTreeNode_t;

一、第 K 層的節點總數

遞歸

規則:空樹或 K ≤ 0 回傳 0;K == 1 時當前節點就是答案,回傳 1;K > 1 則把問題下推一層,求左右子樹的第 K-1 層節點數之和。

int GetBTreeKthLevelNodesTotal(BTreeNode_t *pRoot, int KthLevel)
{
    if (pRoot == NULL || KthLevel <= 0)
        return 0;
    if (KthLevel == 1)
        return 1;

    return GetBTreeKthLevelNodesTotal(pRoot->m_pLeft,  KthLevel - 1)
         + GetBTreeKthLevelNodesTotal(pRoot->m_pRight, KthLevel - 1);
}

非遞歸

用佇列逐層下探,抵達第 K 層時佇列長度就是答案:

int GetKthLevelNodesTotal(BTreeNode_t *pRoot, unsigned int KthLevel)
{
    if (pRoot == NULL) return 0;

    queue<BTreeNode_t *> que;
    que.push(pRoot);
    int curLevelNodesTotal = 0;
    int curLevel = 0;

    while (!que.empty())
    {
        ++curLevel;
        curLevelNodesTotal = que.size();
        if (curLevel == KthLevel) break;         // 佇列裡就是第 K 層

        int cntNode = 0;
        while (cntNode < curLevelNodesTotal)     // 把下一層節點入隊
        {
            ++cntNode;
            pRoot = que.front();
            que.pop();
            if (pRoot->m_pLeft  != NULL) que.push(pRoot->m_pLeft);
            if (pRoot->m_pRight != NULL) que.push(pRoot->m_pRight);
        }
    }

    if (curLevel == KthLevel) return curLevelNodesTotal;
    return 0;    // KthLevel 大於樹的深度
}

二、第 K 層的葉子節點數

遞歸

與上一題只差在 K == 1 時要多問一句:左右子樹是否皆為空。

int GetBTreeKthLevelLeafNodesTotal(BTreeNode_t *pRoot, int KthLevel)
{
    if (pRoot == NULL || KthLevel <= 0)
        return 0;

    if (KthLevel == 1)
    {
        if (pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL)
            return 1;
        else
            return 0;
    }

    return GetBTreeKthLevelLeafNodesTotal(pRoot->m_pLeft,  KthLevel - 1)
         + GetBTreeKthLevelLeafNodesTotal(pRoot->m_pRight, KthLevel - 1);
}

非遞歸

先沿用層序下探到目標層,再把該層節點全部出隊,統計左右皆空者:

if (curLevel == KthLevel)
{
    int cntNode = 0;
    int leafNodes = 0;
    while (cntNode < curLevelNodesTotal)
    {
        ++cntNode;
        pRoot = que.front();
        que.pop();

        if (pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL)
            leafNodes++;
    }
    return leafNodes;
}
return 0;    // KthLevel 大於樹的深度

重點整理

這兩題共用同一個骨架:遞歸版靠「K 減一」把問題往子樹推進,非遞歸版靠「分層出隊」把指標停在目標層。差別只在終端條件要檢查什麼。把這個骨架記熟,第 K 層的各種變形題(求和、求最大值、列印)都能直接套用。

Copyright © Linux教程網 All Rights Reserved