Untitled

 avatar
unknown
plain_text
a month ago
948 B
1
Indexable
public class BSTFromPostorder {
    private int index; // Keeps track of the current root in postorder array.

    public TreeNode constructBST(int[] postorder) {
        index = postorder.length - 1;
        return buildTree(postorder, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }

    private TreeNode buildTree(int[] postorder, int min, int max) {
        // Base condition: If index is out of bounds or element is out of range
        if (index < 0 || postorder[index] < min || postorder[index] > max) {
            return null;
        }

        // The current root is the element at index
        int rootValue = postorder[index--];
        TreeNode root = new TreeNode(rootValue);

        // Build right subtree before left subtree (reverse of postorder traversal)
        root.right = buildTree(postorder, rootValue, max);
        root.left = buildTree(postorder, min, rootValue);

        return root;
    }
}
Leave a Comment