Details
A Cartesian tree of a list is a binary tree constructed so that an in-order traversal of the tree returns the original list, while the tree also satisfies a heap property (either min-heap or max-heap) on the list values. The root is the minimum (or maximum) element of the list, and the left and right subtrees are recursively built from the sublists to the left and right of that element.
If no order function is specified, the input list must contain real values.
The type can be either min-heap (default) or max-heap. In a min-heap, the key at each node is less than or equal to the keys of its children, so the minimum element is always stored at the root. In contrast, a max-heap requires that the key at each node is greater than or equal to the keys of its children, placing the maximum element at the root.
The ordering function
p applies to a pair of elements following the description on the
OrderedQ function page.
The function constructs a Cartesian tree by performing a depth-first search implemented via recursion, where the array is recursively partitioned around its extremal element. At each recursive call, the algorithm identifies the root of the current subtree, then descends into the left and right subarrays to build the corresponding child nodes.