p109 用中序和后序遍历序列构建二叉树(leetcode 106)

一:解题思路

Time:O(n),Space:O(n)

二:完整代码示例 (C++版和Java版)

C++:

class Solution 
{
private:
    TreeNode* buildTree(vector<int>& postorder, int postStart, int postEnd, int inStart, map<int, int>& inPos)
    {
        if (postStart > postEnd) return NULL;
        TreeNode* root = new TreeNode(postorder[postEnd]);
        int rootIdx = inPos[postorder[postEnd]];
        int leftLen = rootIdx - inStart;
        root->left = buildTree(postorder,postStart,postStart+leftLen-1,inStart,inPos);
        root->right = buildTree(postorder,postStart+leftLen,postEnd-1,rootIdx+1,inPos);

        return root;
    }
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) 
    {
        map<int, int> inPos;
        for (int i = 0; i < inorder.size(); i++)
            inPos[inorder[i]] = i;

        return buildTree(postorder,0,postorder.size()-1,0,inPos);
    }
};

 

Java:

class Solution {
        private TreeNode buildTree(int[] postorder,int postStart,int postEnd,int inStart,Map<Integer,Integer> inPos)
        {
                if(postStart>postEnd) return null;
                TreeNode root=new TreeNode(postorder[postEnd]);
                int rootIdx=inPos.get(postorder[postEnd]);
                int leftLen=rootIdx-inStart;
                root.left=buildTree(postorder,postStart,postStart+leftLen-1,inStart,inPos);
                root.right=buildTree(postorder,postStart+leftLen,postEnd-1,rootIdx+1,inPos);
                
                return root;
        }

        public TreeNode buildTree(int[] inorder, int[] postorder)
        {
              Map<Integer,Integer> inPos=new HashMap<>();
              for(int i=0;i<inorder.length;i++)
                  inPos.put(inorder[i],i);

              return buildTree(postorder,0,postorder.length-1,0,inPos);
        }
    }

 

posted @ 2020-04-10 15:46  repinkply  阅读(163)  评论(0)    收藏  举报