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

由前序與中序遍歷重建二元樹:遞歸解法的完整推導

節點定義

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;

核心洞察

兩種遍歷序列各自洩露了不同的資訊:

  • 中序序列的第一個元素,在遞歸的當前子樹中就是根節點(左子樹 → 根 → 右子樹)。
  • 前序序列的第一個元素是根,其左側是左子樹、右側是右子樹。

把兩者結合,就能完成切分:在前序序列中找出中序根節點的位置,這個索引就是左子樹的節點數;剩下的自然就是右子樹的節點數。有了左右子樹各自的節點數,就能算出四段序列的起始位置與長度,於是問題退化為兩個規模更小的同型子問題。

遞歸實作

BTreeNode_t *RebuildBTree(const BTreeNodeElement_t *pPreorder,
                          const BTreeNodeElement_t *pInorder,
                          const int nodesTotal,
                          int (*compare)(const BTreeNodeElement_t*, const BTreeNodeElement_t *))
{
    if (pPreorder == NULL || pInorder == NULL || nodesTotal <= 0 || compare == NULL)
        return NULL;

    BTreeNodeElement_t *pRootData = &pInorder[0];   // 中序首元素即當前子樹的根
    BTreeNode_t *pRoot = new BTreeNode_t;
    pRoot->m_pElemt = pRootData;

    // 在前序序列中定位根,索引即左子樹節點數
    int rootIndex = -1;
    for (int i = 0; i < nodesTotal; ++i)
    {
        if (compare(pRootData, &pPreorder[i]) == 0)
        {
            rootIndex = i;
            break;
        }
    }
    if (rootIndex == -1)
        return NULL;

    // 左子樹:前序從第 2 個元素起,中序從頭起,長度 rootIndex
    int leftNodesTotal = rootIndex;
    BTreeNodeElement_t *pLeftPreorder = pPreorder + 1;
    BTreeNodeElement_t *pLeftInorder  = pInorder;
    pRoot->m_pLeft = RebuildBTree(pLeftPreorder, pLeftInorder, leftNodesTotal, compare);

    // 右子樹:總數減去左子樹與一個根節點
    int rightNodesTotal = nodesTotal - leftNodesTotal - 1;
    BTreeNodeElement_t *pRightPreOrder = pPreorder + leftNodesTotal + 1;
    BTreeNodeElement_t *pRightInorder  = pInorder + leftNodesTotal + 1;
    pRoot->m_pRight = RebuildBTree(pRightPreOrder, pRightInorder, rightNodesTotal, compare);

    return pRoot;
}

複雜度與前提

遞歸深度取決於樹高,最壞情況(退化為鏈表)為 O(n)。每一層都要線性掃描定位根,因此時間複雜度為 O(n log n) 上下;若改用雜湊表預存「值 → 中序索引」,可降到 O(n)。

另外有個前提容易被忽略:演算法要求節點值互不重複,否則定位根節點時會有歧義。實作中若用 compare 函式指標而非直接比較,是為了支援自訂型別的資料,代價是無法做編譯期最佳化。

Copyright © Linux教程網 All Rights Reserved