[Algorithm template] Cartesian tree

[Algorithm template] Cartesian tree

The full text of this article quoted from OI-WIKI see specific link text at the end

This paper describes a less common, but is closely related to the familiar balanced tree with the heap data structure - Cartesian tree.

Cartesian tree is a binary tree, each node of a key-tuple \ ((k, w) \ ) configuration. Requires \ (K \) satisfies the properties of a binary search tree, the \ (W \) satisfy the properties of the stack. An interesting fact is that if the Cartesian tree \ (k, w \) key OK, and \ (k \) different from each other, \ (w \) different from each other, then this is the only tree structure Descartes of. Above:

(Figure from Wikipedia)

The above tree Cartesian tree corresponds to an array element value as the key \ (W \) , and the key array as a subscript \ (K \) . Obviously you can find this tree key \ (k \) to meet the nature of binary search tree, and the key \ (w \) to meet the nature of small root of the heap.

In fact, the figure Cartesian tree is a special case, because the key-tuple \ (K \) corresponds exactly to the array index, this special nature of a Cartesian tree, is a sub-tree under the standard is a continuous interval (in order to meet the nature of the binary search tree). The more general case of any tuple is constructed Cartesian tree.

Construct

Stack building

We consider the elements in accordance with the key \ (k \) sort. A current is then inserted into a Cartesian tree. So every time we insert the right chain of inevitable element in this tree: the end (that is, from the right chain has been taking root right subtree, after the formation of the node) of. So we perform such a process, from the bottom up and right hinge point and comparing the current node \ (U \) a \ (W \) , if find a node on the right chain \ (X \) satisfies \ ( x_w <u_w \) , put \ (u \) to the son on the right of x, and x original right subtree becomes u left subtree.

No specific explanation, we directly on the map. The red frame part is that we always maintain the right chain:

Each number is obviously up to the right and out of a chain (or each point exists in the right chain is a contiguous time). We can use this process to maintain the stack, the stack to maintain the current node on the right chain Cartesian tree. A point not put it on the right chain flicked. Up to this point out each time, the complexity of the \ (O (n-) \) . Pseudo-code as follows:

新建一个大小为 n 的空栈。用 top 来标操作前的栈顶,k 来标记当前栈顶。
For i := 1 to n
    k := top
    While 栈非空 且 栈顶元素 > 当前元素 
        k--
    if 栈非空
        栈顶元素.右儿子 := 当前元素
    if k < top
        当前元素.左儿子 := 栈顶元素
    当前元素入栈
    top := k

Reference material

Cartesian tree

Wikipedia - Cartesian tree

Guess you like

Origin www.cnblogs.com/GavinZheng/p/11831305.html