Build a Cartesian Tree from an array of integers in O(n) time using a stack-based approach. A Cartesian Tree is a binary tree derived from a sequence of numbers with these properties:
1. Binary Search Tree (BST) property: In-order traversal gives the original array sequence
2. Min-Heap property: Each parent node has a value smaller than both children
Your task is to construct the tree and verify both properties hold. Return a list containing two boolean values: [isBST, isMinHeap] where the first indicates if the BST property holds and the second indicates if the min-heap property holds.
Note: The tree structure is uniquely determined by the array values and their positions.
Input & Output
Example 1 — Basic Case
$Input:arr = [3,1,6,4,5]
›Output:[true,true]
💡 Note:Cartesian tree has 1 as root (minimum), 3 as left child, and 6,4,5 form right subtree. In-order traversal gives [3,1,6,4,5] (BST property ✓) and all parents are smaller than children (min-heap property ✓)
Example 2 — All Increasing
$Input:arr = [1,2,3,4,5]
›Output:[true,true]
💡 Note:Creates a right-skewed tree with 1 as root. In-order traversal: [1,2,3,4,5] (BST ✓). Each parent < children (min-heap ✓)
Example 3 — All Decreasing
$Input:arr = [5,4,3,2,1]
›Output:[true,true]
💡 Note:Creates a left-skewed tree with 1 as root at the end. In-order: [5,4,3,2,1] (BST ✓). Min-heap property holds (min-heap ✓)
The key insight is using a stack to maintain the rightmost path while building the Cartesian tree. The optimal stack-based approach achieves O(n) time by processing each element exactly once. Time: O(n), Space: O(n).
Common Approaches
✓
Brute Force Recursive
⏱️ Time: O(n²)
Space: O(n)
Find the minimum element in the array to use as root, then recursively build left subtree from elements to the left and right subtree from elements to the right. Finally verify both BST and min-heap properties.
Stack-Based O(n)
⏱️ Time: O(n)
Space: O(n)
Build the tree using a stack to maintain the rightmost path from root. For each element, pop from stack until finding the correct parent, then insert the new node appropriately.
Brute Force Recursive — Algorithm Steps
Step 1: Find minimum element index in current array segment
Step 2: Make minimum element the root of current subtree
Step 3: Recursively build left subtree from left portion
Step 4: Recursively build right subtree from right portion