题目六:重建二叉树

Posted yzdai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了题目六:重建二叉树相关的知识,希望对你有一定的参考价值。

///////////////////////////////////////////////////////////////////////////////////////
// // 9.题目六:重建二叉树
// 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出改二叉树


struct BinaryTreeNode

    int m_iValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;

    BinaryTreeNode(int iValue = 0, BinaryTreeNode* pLeft = NULL, BinaryTreeNode* pRight = NULL)
        :m_iValue(iValue), m_pLeft(pLeft), m_pRight(pRight)
    

    
;

BinaryTreeNode* RebuildTree(int* pPreStart, int* pPreEnd, int* pInStart, int* pInEnd)

    if (pPreStart > pPreEnd || pInStart > pInEnd)
    
        return NULL;
    

    // 1.建立根节点(前序遍历第一个元素)
    BinaryTreeNode* pRoot = new BinaryTreeNode(*pPreStart);
    if (!pRoot)
    
        return NULL;
    

    // 2.找到中序根节点
    int* p = pInStart;
    while (p <= pInEnd && *p != pRoot->m_iValue)
    
        p++;
    

    int iLeftLength = p - pInStart;
    int* pLeftPreEnd = pPreStart + iLeftLength;

    // 3.构建左子树
    if (iLeftLength > 0)
    
        pRoot->m_pLeft = RebuildTree(pPreStart + 1, pLeftPreEnd, pInStart, p - 1);
    

    // 4.构建右子树
    if (iLeftLength < (pPreEnd - pPreStart))
    
        pRoot->m_pRight = RebuildTree(pLeftPreEnd + 1, pPreEnd, p + 1, pInEnd);
    

    return pRoot;


BinaryTreeNode* RebuildBinaryTree(int* piPreOrderArray, int* piInorderArray, int iLength)

    if (NULL == piPreOrderArray || NULL == piInorderArray || iLength <= 0)
    
        return NULL;
    

    return RebuildTree(piPreOrderArray, piPreOrderArray + iLength - 1, piInorderArray, piInorderArray + iLength -1);


void DestroyTree(BinaryTreeNode* pTree)

    if (pTree)
    
        // 释放左子树
        DestroyTree(pTree->m_pLeft);

        // 释放右子树
        DestroyTree(pTree->m_pRight);

        delete pTree;
        pTree = NULL;
    


// 后序遍历
void PostTraversal(BinaryTreeNode* pNode)

    if (pNode)
    
        PostTraversal(pNode->m_pLeft);
        PostTraversal(pNode->m_pRight);
        printf("%02d -> ", pNode->m_iValue);
    


void RebuildBinaryTreeTestFunc()

    cout << "\n\n --------------- RebuildBinaryTreeTestFunc Start -------------->" << endl;
    const int MAX_TREE_NODE_COUNT = 8;

    //前序遍历序列(中 -> 左 -> 右)
    int aiPreOrderArray[MAX_TREE_NODE_COUNT] = 1, 2, 4, 7, 3, 5, 6, 8;

    //中序遍历序列(左 -> 中 -> 右)
    int aiInorderArray[MAX_TREE_NODE_COUNT] = 4, 7, 2, 1, 5, 3, 8, 6;

    //后序遍历序列(左 -> 右 -> 中)
    int aiPostArray[MAX_TREE_NODE_COUNT] = 7, 4, 2, 5, 8, 6, 3, 1;

    BinaryTreeNode* pTree1 = RebuildBinaryTree(aiPreOrderArray, aiInorderArray, MAX_TREE_NODE_COUNT);
    if (pTree1)
    
        // 后序遍历
        PostTraversal(pTree1);
        putchar(10);

        // 施法资源
        DestroyTree(pTree1);
    

    cout << "\n\n --------------- RebuildBinaryTreeTestFunc End -------------->" << endl;

以上是关于题目六:重建二叉树的主要内容,如果未能解决你的问题,请参考以下文章

Java面试:重建二叉树题目

算法题17 重建二叉树

题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树

重建二叉树

剑指offer 重建二叉树

剑指offer-重建二叉树