重建二叉树*

struct BinaryTreeNode {
    int nValue;
    BinaryTreeNode* pLeft;
    BinaryTreeNode* pRight;
};

BinaryTreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder)
{
    int rootValue = startPreorder[0];
    BinaryTreeNode* pRoot = new BinaryTreeNode();
    pRoot->nValue = rootValue;
    pRoot->pLeft = pRoot->pRight = nullptr;

    if (startPreorder == endPreorder)
    {
        if (startInorder == endInorder && *startPreorder == *startInorder)
            return pRoot;
        else
            throw std::exception("Invalid input");
    }
    //在中序遍历中找到根节点的值
    int* rootInorder = startInorder;
    while (rootInorder <= endInorder && *rootInorder != rootValue)
        ++rootInorder;

    if(rootInorder == endInorder && *rootInorder != rootValue)
        throw std::exception("Invalid input");

    int leftLength = rootInorder - startInorder;
    int* leftPreorder = startPreorder + leftLength;
    if (leftLength > 0)
    {
        //构建左子树
        pRoot->pLeft = ConstructCore(startPreorder + 1, leftPreorder, startInorder, rootInorder -1);
    }
    if (leftLength < endPreorder - startPreorder)
    {
        //构建右子树
        pRoot->pRight = ConstructCore(leftPreorder +1, endPreorder, rootInorder+1, endInorder);
    }
    return pRoot;
}
BinaryTreeNode* Construct(int* preorder, int* inorder, int length)
{
    if (nullptr == preorder || nullptr == inorder || length <= 0)
        return nullptr;
    
    return ConstructCore(preorder, preorder + length - 1, inorder, inorder + length - 1);

}

 

posted on 2021-01-26 15:53  Noora&w  阅读(59)  评论(0编辑  收藏  举报