Java Recursive Solution without Constructing Helper Function


  • 0

    Very similar to my recursive solution of Q105.

    public TreeNode buildTree(int[] inorder, int[] postorder) {
            int n = inorder.length;
            // Base case.
            if(n == 0)
                return null;
            // General case.
            int rootVal = postorder[n-1];
            int rootIndex = 0;
            for(int i = 0; i < n; i++) {
                if(inorder[i] == rootVal) {
                    rootIndex = i;
                    break;
                }
            }
            int leftLength = rootIndex;
            int rightLength = n - 1 - leftLength;
            TreeNode root = new TreeNode(rootVal);
            root.left = buildTree(Arrays.copyOfRange(inorder, 0, leftLength), Arrays.copyOfRange(postorder, 0, leftLength));
            root.right = buildTree(Arrays.copyOfRange(inorder, rootIndex + 1, rootIndex + 1 + rightLength), Arrays.copyOfRange(postorder, leftLength, leftLength + rightLength));
            return root;
        }
    

Log in to reply
 

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