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);
    
    }
  • 相关阅读:
    java7或java8新特性
    反射中,Class.forName和ClassLoader区别
    &和&&的区别
    JAVA时区问题总结
    索引失效原因及解决索引失效方法
    索引失效的7种情况
    MySQL Explain详解
    java switch
    java 生成注释文档
    spring 获取配置文件的值
  • 原文地址:https://www.cnblogs.com/yapp/p/14330798.html
Copyright © 2011-2022 走看看