Java recursive approach without helper function


  • 0
    W
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            if(inorder.length == 0 || postorder.length == 0 || inorder.length != postorder.length)  return null;
            
            int val = postorder[postorder.length - 1];
            TreeNode root = new TreeNode(val);
            int index = 0;
            while(inorder[index] != val)    index++;
            root.left = buildTree(Arrays.copyOfRange(inorder, 0,index), Arrays.copyOfRange(postorder, 0, index));
            root.right = buildTree(Arrays.copyOfRange(inorder, index+1,inorder.length), Arrays.copyOfRange(postorder, index, postorder.length-1));
            return root;
        }
    }

Log in to reply
 

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