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);
    
    }
  • 相关阅读:
    Fluent API
    什么是blazor
    10.事务
    9.用ExecuteSqlCommand执行存储过程
    8.自增主键 插入指定主键的数据
    7.图
    6.实体与上下文的关系
    5.并发
    4.跟踪
    3.级联删除
  • 原文地址:https://www.cnblogs.com/yapp/p/14330798.html
Copyright © 2011-2022 走看看