Cartesian Tree Builder - Problem
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 ✓)
Constraints
- 1 ≤ arr.length ≤ 1000
- 1 ≤ arr[i] ≤ 1000
- All elements in arr are distinct
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code