zoukankan      html  css  js  c++  java
  • 重建二叉树*

    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);
    
    }
  • 相关阅读:
    WSL+vscode安装rust注意事项
    几种判断质数的算法
    select被遮挡问题
    idea工具使用
    docker部署nexus服务
    docker部署nacos
    springcloudAlibaba整合nacos
    Navicat_Premium_v15 激活
    CF295D Solution
    CF351B Solution
  • 原文地址:https://www.cnblogs.com/yapp/p/14330798.html
Copyright © 2011-2022 走看看