Given an array representing a Postorder Traversal of a Binary Tree, determine whether the possible binary tree formed from it can qualify as a Binary Search Tree (BST).
A Binary Search Tree is defined as:
For every node in the tree:
Left subtree nodes’ values are less than the node’s value.
Right subtree nodes’ values are greater than the node’s value.
Input: postorder =[1,3,2,6,5]Output: False
Explanation: This postorder traversal cannot form any valid Binary Search Tree because 6 exists on the left side of 5, violating the BST property.
classSolution {
publicbooleanisPostOrderBST(int[] postorder) {
return isPostOrderBSTHelper(postorder, 0, postorder.length- 1);
}
privatebooleanisPostOrderBSTHelper(int[] postorder, int start, int end) {
if (start >= end) {
returntrue; // Single element or empty -> valid BST }
// Last element is the rootint root = postorder[end];
int i = start;
// Find boundary between left and right subtreewhile (i < end && postorder[i]< root) {
i++;
}
// Verify that all elements in the 'right subtree' are greater than rootfor (int j = i; j < end; j++) {
if (postorder[j]< root) {
returnfalse; // Violates BST property }
}
// Recursively check left and right subtreesreturn (
isPostOrderBSTHelper(postorder, start, i - 1) && isPostOrderBSTHelper(postorder, i, end - 1)
);
}
// Main function for testing examplespublicstaticvoidmain(String[] args) {
Solution solution =new Solution();
// Example 1int[] postorder1 = { 2, 4, 3, 8, 7, 5 };
System.out.println(solution.isPostOrderBST(postorder1)); // Output: True// Example 2int[] postorder2 = { 1, 3, 2, 6, 5 };
System.out.println(solution.isPostOrderBST(postorder2)); // Output: False }
}
classSolution:
defisPostOrderBST(self, postorder):
defhelper(start, end):
if start >= end:
returnTrue# Single element or empty -> valid BST# Last element is the root root = postorder[end]
i = start
# Find boundary between left and right subtreewhile i < end and postorder[i] < root:
i +=1# Verify that all elements in the 'right subtree' are greater than rootfor j in range(i, end):
if postorder[j] < root:
returnFalse# Violates BST property# Recursively check left and right subtreesreturn helper(start, i -1) and helper(i, end -1)
# Trigger helper recursivelyreturn helper(0, len(postorder) -1)
# Main function for testing examplesif __name__ =="__main__":
solution = Solution()
# Example 1 postorder1 = [2, 4, 3, 8, 7, 5]
print(solution.isPostOrderBST(postorder1)) # Output: True# Example 2 postorder2 = [1, 3, 2, 6, 5]
print(solution.isPostOrderBST(postorder2)) # Output: False
⏰ Time complexity: O(n^2). In the worst case, every check requires scanning the entire subtree (n) for splitting into left and right sections. For n elements, the complexity is quadratic.
🧺 Space complexity: O(n). Recursive stack calls take at most n space in the worst case (single branch tree).