106. Construct Binary Tree from Inorder and Postorder Traversal

欢迎fork and star:Nowcoder-Repository-github

106. Construct Binary Tree from Inorder and Postorder Traversal

题目

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

Note:
You may assume that duplicates do not exist in the tree. 

解析

// 106. Construct Binary Tree from Inorder and Postorder Traversal
class Solution_106 {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { //这样消耗内存多些
        
        if (inorder.size()==0||postorder.size()==0||inorder.size()!=postorder.size())
        {
            return NULL;
        }

        int len = postorder.size();
        TreeNode* root = new TreeNode(postorder[len-1]);
        
        //bug:
        //terminate called after throwing an instance of 'std::bad_alloc'
        //what() : std::bad_alloc

        auto pos = find(inorder.begin(), inorder.end(), postorder[len - 1]);
        vector<int> inorder_l(inorder.begin(),pos);
        vector<int> inorder_r(pos + 1, inorder.end());
        vector<int> postorder_l(postorder.begin(), postorder.begin() + inorder_l.size());
        vector<int> postorder_r(postorder.begin()+inorder_l.size(),postorder.end()-1);
        
        if (inorder_l.size()>0)
        {
            root->left = buildTree(inorder_l, postorder_l);
        }

        if (inorder_r.size()>0)
        {
            root->right = buildTree(inorder_r, postorder_r);
        }
        
        return root;
    }


public:
    TreeNode* buildTreeHelper(vector<int>& inorder, int l1, int r1, vector<int>& postorder, int l2, int r2) //在原数组上操作,不需要额外空间
    {
        if (l1>r1||l2>r2)
        {
            return NULL;
        }
        
        TreeNode* root = new TreeNode(postorder[r2]);
        int i = 0;
        for ( i= l1; i <= r1;i++) // for ( i= 0; i < inorder.size();i++) //递归实现参数要能进入下次递归
        {
            if (inorder[i]==postorder[r2])
            {
                break;
            }
        }

        root->left = buildTreeHelper(inorder,l1,i-1,postorder,l2,l2+(i-1-l1)); //慢慢体会下标的准确性
        root->right = buildTreeHelper(inorder, i + 1, r1, postorder, l2 + (i - l1), r2-1);

        return root;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) 
    {
        if (inorder.size()==0||postorder.size()==0||inorder.size()!=postorder.size())
        {
            return NULL;
        }

        return buildTreeHelper(inorder, 0, inorder.size() - 1, postorder,0, postorder.size() - 1);
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8259578.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞