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);
    
    }
  • 相关阅读:
    NSUserDefaults
    版本控制
    真机调试流程
    UIImageView加载图片的两种方式
    UI控件之--UIButton
    Xcode错误总结
    自动布局AutoLayout
    地理编码和反地理编码
    WordPress NOSpam PTI插件‘comment_post_ID’参数SQL注入漏洞
    WordPress RokMicroNews插件‘thumb.php’ 多个安全漏洞
  • 原文地址:https://www.cnblogs.com/yapp/p/14330798.html
Copyright © 2011-2022 走看看