73_leetcode_Construct Binary Tree from Inorder and Postorder Traversal

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了73_leetcode_Construct Binary Tree from Inorder and Postorder Traversal相关的知识,希望对你有一定的参考价值。


Given inorder and postorder traversal of a tree, construct the binary tree

1:中序和后序遍历构成一棵树。2:採用递归的方法。3:把两个数组分别分成两部分;4:注意递归结束情况


    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
    {
        if(inorder.size() == 0 || postorder.size() == 0 || inorder.size() != postorder.size())
        {
            return NULL;
        }
        
        int size = (int)inorder.size();
        return buildTreeCore(inorder, 0, postorder, 0, size);
    }
    
    TreeNode *buildTreeCore(vector<int> &inorder, int inStart, vector<int> &postorder, int postStart, int length)
    {
        if(length == 1)
        {
            if(inorder[inStart] != postorder[postStart])
            {
                return NULL;
            }
        }
        
        int rootValue = postorder[postStart + length - 1];
        TreeNode *root = new TreeNode(rootValue);
        
        int i = 0;
        for(; i < length; i++)
        {
            if(inorder[inStart + i] == rootValue)
            {
                break;
            }
        }
        
        if(i == length)
        {
            return NULL;
        }
        
        if(i > 0)
        {
            root->left = buildTreeCore(inorder, inStart, postorder, postStart, i);
        }
        
        if(i < length - 1)
        {
            root->right = buildTreeCore(inorder, inStart + i + 1, postorder, postStart + i, length - i - 1);
        }

        return root;
    }


以上是关于73_leetcode_Construct Binary Tree from Inorder and Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

Windows下Elasticsearch安装问题处理

LeetCode_Construct Binary Tree from Inorder and Postorder Traversal

Redhat 启动mysql失败及重置密码

QT 编写的程序进行打包

QT 编写的程序进行打包

System.properties