Java recursive solution


  • 0
    S
    public TreeNode buildTree(int[] inorder, int[] postorder) {
            if(inorder.length == 0) return null;
            HashMap<Integer, Integer> map = new HashMap<>();
            for(int i = 0; i < inorder.length; i++)
                map.put(inorder[i], i);
            TreeNode root = helper(postorder, 0, inorder.length - 1, 0, postorder.length - 1, map);
            return root;
        }
        
        private TreeNode helper(int[] postorder, int is, int ie, int ps, int pe, HashMap<Integer, Integer> map){
            if(ps > pe) return null;
            if(ps == pe) return new TreeNode(postorder[pe]);
            TreeNode root = new TreeNode(postorder[pe]);
            int index = map.get(postorder[pe]);
            root.left = helper(postorder, is, index - 1, ps, pe - ie + index - 1, map);
            root.right = helper(postorder,index + 1, ie, pe - ie + index, pe - 1, map);
            return root;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.