Cartesian Tree
见 www.geeksforgeeks.org/cartesian-t…
A Cartesian([kɑː'tiːziən]) tree is a tree data structure created from a set of data that obeys the following structural invariants:
- The tree obeys the min (or max) heap property – each node is less (or greater) than its children.
- An inorder traversal of the nodes yields the values in the same order in which they appear in the initial sequence.
Suppose we have an input array {5,10,40,30,28}. Then the max-heap Cartesian Tree would be.
A min-heap Cartesian Tree of the above input array will be-
value 在图中是节点高度, index在图中是左右位置
Note:
- Cartesian Tree is not a height-balanced tree.
- Cartesian tree of a sequence of distinct numbers is always unique.
How to construct Cartesian Tree
A O(nlogn) Algorithm :
It’s possible to build a Cartesian tree from a sequence of data in O(NlogN) time on average. Beginning with the empty tree,
Scan the given sequence from left to right adding new nodes as follows:
- Position the node as the right child of the rightmost node.
- Scan upward from the node’s parent up to the root of the tree until a node is found whose value is greater than the current value.
- If such a node is found, set its right child to be the new node, and set the new node’s left child to be the previous right child.
- If no such node is found, set the new child to be the root, and set the new node’s left child to be the previous tree.
application
- Cartesian Tree Sorting
- A range minimum query on a sequence is equivalent to a lowest common ancestor query on the sequence’s Cartesian tree. Hence, RMQ may be reduced to LCA using the sequence’s Cartesian tree.
- Treap, a balanced binary search tree structure, is a Cartesian tree of (key,priority) pairs; it is heap-ordered according to the priority values, and an inorder traversal gives the keys in sorted order.
- Suffix tree of a string may be constructed from the suffix array and the longest common prefix array. The first step is to compute the Cartesian tree of the longest common prefix array.