Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Cartesian tree

This is a good article. Click here for more information.
From Wikipedia, the free encyclopedia

Binary tree derived from a sequence of numbers
A sequence of numbers and the Cartesian tree derived from them.
For Descartes' metaphor of tree of knowledge, seeTree of knowledge (philosophy).

Incomputer science, aCartesian tree is abinary tree derived from a sequence of distinct numbers. To construct the Cartesian tree, set its root to be the minimum number in the sequence, and recursively construct its left and right subtrees from the subsequences before and after this number. It is uniquely defined as amin-heap whosesymmetric (in-order) traversal returns the original sequence.

Cartesian trees were introduced byVuillemin (1980) in the context of geometricrange searching data structures. They have also been used in the definition of thetreap andrandomized binary search tree data structures forbinary search problems, incomparison sort algorithms that perform efficiently on nearly-sorted inputs, and as the basis forpattern matching algorithms. A Cartesian tree for a sequence can be constructed inlinear time.

Definition

[edit]

Cartesian trees are defined usingbinary trees, which are a form ofrooted tree. To construct the Cartesian tree for a given sequence of distinct numbers, set its root to be the minimum number in the sequence,[1] andrecursively construct its left and right subtrees from the subsequences before and after this number, respectively. As a base case, when one of these subsequences is empty, there is no left or right child.[2]

It is also possible to characterize the Cartesian tree directly rather than recursively, using its ordering properties. In any tree, thesubtree rooted at any node consists of all other nodes that can reach it by repeatedly following parent pointers. The Cartesian tree for a sequence of distinct numbers is defined by the following properties:

  1. The Cartesian tree for a sequence is abinary tree with one node for each number in the sequence.
  2. Asymmetric (in-order) traversal of the tree results in the original sequence. Equivalently, for each node, the numbers in its left subtree are earlier than it in the sequence, and the numbers in the right subtree are later.
  3. The tree has themin-heap property: the parent of any non-root node has a smaller value than the node itself.[1]

These two definitions are equivalent: the tree defined recursively as described above is the unique tree that has the properties listed above. If a sequence of numbers contains repetitions, a Cartesian tree can be determined for it by following a consistent tie-breaking rule before applying the above construction. For instance, the first of two equal elements can be treated as the smaller of the two.[2]

History

[edit]

Cartesian trees were introduced and named byVuillemin (1980), who used them as an example of the interaction betweengeometric combinatorics and the design and analysis ofdata structures. In particular, Vuillemin used these structures to analyze theaverage-case complexity of concatenation and splitting operations onbinary search trees. The name is derived from theCartesian coordinate system for the plane: in one version of this structure, as in the two-dimensional range searching application discussed below, a Cartesian tree for a point set has the sorted order of the points by theirx{\displaystyle x}-coordinates as its symmetric traversal order, and it has the heap property according to they{\displaystyle y}-coordinates of the points. Vuillemin described both this geometric version of the structure, and the definition here in which a Cartesian tree is defined from a sequence. Using sequences instead of point coordinates provides a more general setting that allows the Cartesian tree to be applied to non-geometric problems as well.[2]

Efficient construction

[edit]

A Cartesian tree can be constructed inlinear time from its input sequence.One method is to process the sequence values in left-to-right order, maintaining the Cartesian tree of the nodes processed so far, in a structure that allows both upwards and downwards traversal of the tree. To process each new valuea{\displaystyle a}, start at the node representing the value prior toa{\displaystyle a} in the sequence and follow thepath from this node to the root of the tree until finding a valueb{\displaystyle b} smaller thana{\displaystyle a}. The nodea{\displaystyle a} becomes the right child ofb{\displaystyle b}, and the previous right child ofb{\displaystyle b} becomes the new left child ofa{\displaystyle a}. The total time for this procedure is linear, because the time spent searching for the parentb{\displaystyle b} of each new nodea{\displaystyle a} can becharged against the number of nodes that are removed from the rightmost path in the tree.[3]

An alternative linear-time construction algorithm is based on theall nearest smaller values problem. In the input sequence, define theleft neighbor of a valuea{\displaystyle a} to be the value that occurs prior toa{\displaystyle a}, is smaller thana{\displaystyle a}, and is closer in position toa{\displaystyle a} than any other smaller value. Theright neighbor is defined symmetrically. The sequence of left neighbors can be found by an algorithm that maintains astack containing a subsequence of the input. For each new sequence valuea{\displaystyle a}, the stack is popped until it is empty or its top element is smaller thana{\displaystyle a}, and thena{\displaystyle a} is pushed onto the stack. The left neighbor ofa{\displaystyle a} is the top element at the timea{\displaystyle a} is pushed. The right neighbors can be found by applying the same stack algorithm to the reverse of the sequence. The parent ofa{\displaystyle a} in the Cartesian tree is either the left neighbor ofa{\displaystyle a} or the right neighbor ofa{\displaystyle a}, whichever exists and has a larger value. The left and right neighbors can also be constructed efficiently byparallel algorithms, making this formulation useful in efficient parallel algorithms for Cartesian tree construction.[4]

Another linear-time algorithm for Cartesian tree construction is based ondivide-and-conquer. The algorithm recursively constructs the tree on each half of the input, and then merges the two trees. The merger process involves only the nodes on the left and rightspines of these trees: the left spine is the path obtained by following left child edges from the root until reaching a node with no left child, and the right spine is defined symmetrically. As with any path in a min-heap, both spines have their values in sorted order, from the smallest value at their root to their largest value at the end of the path. To merge the two trees, apply amerge algorithm to the right spine of the left tree and the left spine of the right tree, replacing these two paths in two trees by a single path that contains the same nodes. In the merged path, the successor in the sorted order of each node from the left tree is placed in its right child, and the successor of each node from the right tree is placed in its left child, the same position that was previously used for its successor in the spine. The left children of nodes from the left tree and right children of nodes from the right tree remain unchanged. The algorithm is parallelizable since on each level of recursion, each of the two sub-problems can be computed in parallel, and the merging operation can beefficiently parallelized as well.[5]

Yet another linear-time algorithm, using a linked list representation of the input sequence, is based onlocally maximum linking: the algorithm repeatedly identifies alocal maximum element, i.e., one that is larger than both its neighbors (or than its only neighbor, in case it is the first or last element in the list). This element is then removed from the list, and attached as the right child of its left neighbor, or the left child of its right neighbor, depending on which of the two neighbors has a larger value, breaking ties arbitrarily. This process can be implemented in a single left-to-right pass of the input, and it is easy to see that each element can gain at most one left-, and at most one right child, and that the resulting binary tree is a Cartesian tree of the input sequence.[6][7]

It is possible to maintain the Cartesian tree of a dynamic input, subject to insertions of elements andlazy deletion of elements, in logarithmicamortized time per operation. Here, lazy deletion means that a deletion operation is performed by marking an element in the tree as being a deleted element, but not actually removing it from the tree. When the number of marked elements reaches a constant fraction of the size of the whole tree, it is rebuilt, keeping only its unmarked elements.[8]

Applications

[edit]

Range searching and lowest common ancestors

[edit]
Two-dimensional range-searching using a Cartesian tree: the bottom point (red in the figure) within a three-sided region with two vertical sides and one horizontal side (if the region is nonempty) can be found as the nearest common ancestor of the leftmost and rightmost points (the blue points in the figure) within the slab defined by the vertical region boundaries. The remaining points in the three-sided region can be found by splitting it by a vertical line through the bottom point and recursing.

Cartesian trees form part of an efficient data structure forrange minimum queries. An input to this kind of query specifies a contiguous subsequence of the original sequence; the query output should be the minimum value in this subsequence.[9] In a Cartesian tree, this minimum value can be found at thelowest common ancestor of the leftmost and rightmost values in the subsequence. For instance, in the subsequence (12,10,20,15,18) of the example sequence, the minimum value of the subsequence (10) forms the lowest common ancestor of the leftmost and rightmost values (12 and 18). Because lowest common ancestors can be found in constant time per query, using a data structure that takes linear space to store and can be constructed in linear time, the same bounds hold for the range minimization problem.[10]

Bender & Farach-Colton (2000) reversed this relationship between the two data structure problems by showing that data structures for range minimization could also be used for finding lowest common ancestors. Their data structure associates with each node of the tree its distance from the root, and constructs a sequence of these distances in the order of anEuler tour of the (edge-doubled) tree. It then constructs a range minimization data structure for the resulting sequence. The lowest common ancestor of any two vertices in the given tree can be found as the minimum distance appearing in the interval between the initial positions of these two vertices in the sequence. Bender and Farach-Colton also provide a method for range minimization that can be used for the sequences resulting from this transformation, which have the special property that adjacent sequence values differ by one. As they describe, for range minimization in sequences that do not have this form, it is possible to use Cartesian trees to reduce the range minimization problem to lowest common ancestors, and then to use Euler tours to reduce lowest common ancestors to a range minimization problem with this special form.[11]

The same range minimization problem may also be given an alternative interpretation in terms of two dimensional range searching. A collection of finitely many points in theCartesian plane can be used to form a Cartesian tree, by sorting the points by theirx{\displaystyle x}-coordinates and using they{\displaystyle y}-coordinates in this order as the sequence of values from which this tree is formed. IfS{\displaystyle S} is the subset of the input points within some vertical slab defined by the inequalitiesLxR{\displaystyle L\leq x\leq R},p{\displaystyle p} is the leftmost point inS{\displaystyle S} (the one with minimumx{\displaystyle x}-coordinate), andq{\displaystyle q} is the rightmost point inS{\displaystyle S} (the one with maximumx{\displaystyle x}-coordinate) then the lowest common ancestor ofp{\displaystyle p} andq{\displaystyle q} in the Cartesian tree is the bottommost point in the slab. A three-sided range query, in which the task is to list all points within a region bounded by the three inequalitiesLxR{\displaystyle L\leq x\leq R} andyT{\displaystyle y\leq T}, can be answered by finding this bottommost pointb{\displaystyle b}, comparing itsy{\displaystyle y}-coordinate toT{\displaystyle T}, and (if the point lies within the three-sided region) continuing recursively in the two slabs bounded betweenp{\displaystyle p} andb{\displaystyle b} and betweenb{\displaystyle b} andq{\displaystyle q}. In this way, after the leftmost and rightmost points in the slab are identified, all points within the three-sided region can be listed in constant time per point.[3]

The same construction, of lowest common ancestors in a Cartesian tree, makes it possible to construct a data structure with linear space that allows the distances between pairs of points in anyultrametric space to be queried in constant time per query. The distance within an ultrametric is the same as theminimax path weight in theminimum spanning tree of the metric.[12] From the minimum spanning tree, one can construct a Cartesian tree, the root node of which represents the heaviest edge of the minimum spanning tree. Removing this edge partitions the minimum spanning tree into two subtrees, and Cartesian trees recursively constructed for these two subtrees form the children of the root node of the Cartesian tree. The leaves of the Cartesian tree represent points of the metric space, and the lowest common ancestor of two leaves in the Cartesian tree is the heaviest edge between those two points in the minimum spanning tree, which has weight equal to the distance between the two points. Once the minimum spanning tree has been found and its edge weights sorted, the Cartesian tree can be constructed in linear time.[13]

As a binary search tree

[edit]
Main article:Treap

The Cartesian tree of a sorted sequence is just apath graph, rooted at its leftmost endpoint. Binary searching in this tree degenerates tosequential search in the path. However, a different construction uses Cartesian trees to generatebinary search trees of logarithmic depth from sorted sequences of values. This can be done by generatingpriority numbers for each value, and using the sequence of priorities to generate a Cartesian tree. This construction may equivalently be viewed in the geometric framework described above, in which thex{\displaystyle x}-coordinates of a set of points are the values in a sorted sequence and they{\displaystyle y}-coordinates are their priorities.[14]

This idea was applied bySeidel & Aragon (1996), who suggested the use of random numbers as priorities. Theself-balancing binary search tree resulting from this random choice is called atreap, due to its combination of binary search tree and min-heap features. An insertion into a treap can be performed by inserting the new key as a leaf of an existing tree, choosing a priority for it, and then performingtree rotation operations along a path from the node to the root of the tree to repair any violations of the heap property caused by this insertion; a deletion can similarly be performed by a constant amount of change to the tree followed by a sequence of rotations along a single path in the tree.[14] A variation on this data structure called a zip tree uses the same idea of random priorities, but simplifies the random generation of the priorities, and performs insertions and deletions in a different way, by splitting the sequence and its associated Cartesian tree into two subsequences and two trees and then recombining them.[15]

If the priorities of each key are chosen randomly and independently once whenever the key is inserted into the tree, the resulting Cartesian tree will have the same properties as arandom binary search tree, a tree computed by inserting the keys in a randomly chosenpermutation starting from an empty tree, with each insertion leaving the previous tree structure unchanged and inserting the new node as a leaf of the tree. Random binary search trees have been studied for much longer than treaps, and are known to behave well as search trees. Theexpected length of the search path to any given value is at most2lnn{\displaystyle 2\ln n}, and the whole tree haslogarithmic depth (its maximum root-to-leaf distance)with high probability. More formally, there exists a constantC{\displaystyle C} such that the depth isClnn{\displaystyle \leq C\ln n} with probability tending to one as the number of nodes tends to infinity. The same good behavior carries over to treaps. It is also possible, as suggested by Aragon and Seidel, to reprioritize frequently-accessed nodes, causing them to move towards the root of the treap and speeding up future accesses for the same keys.[14]

In sorting

[edit]
Pairs of consecutive sequence values (shown as the thick red edges) that bracket a sequence value (the darker blue point). The cost of including this value in the sorted order produced by the Levcopoulos–Petersson algorithm is proportional to thelogarithm of this number of bracketing pairs.

Levcopoulos & Petersson (1989) describe asorting algorithm based on Cartesian trees. They describe the algorithm as based on a tree with the maximum at the root,[16] but it can be modified straightforwardly to support a Cartesian tree with the convention that the minimum value is at the root. For consistency, it is this modified version of the algorithm that is described below.

The Levcopoulos–Petersson algorithm can be viewed as a version ofselection sort orheap sort that maintains apriority queue of candidate minima, and that at each step finds and removes the minimum value in this queue, moving this value to the end of an output sequence. In their algorithm, the priority queue consists only of elements whose parent in the Cartesian tree has already been found and removed. Thus, the algorithm consists of the following steps:[16]

  1. Construct a Cartesian tree for the input sequence
  2. Initialize a priority queue, initially containing only the tree root
  3. While the priority queue is non-empty:
    • Find and remove the minimum value in the priority queue
    • Add this value to the output sequence
    • Add the Cartesian tree children of the removed value to the priority queue

As Levcopoulos and Petersson show, for input sequences that are already nearly sorted, the size of the priority queue will remain small, allowing this method to take advantage of the nearly-sorted input and run more quickly. Specifically, the worst-case running time of this algorithm isO(nlogk){\displaystyle O(n\log k)}, wheren{\displaystyle n} is the sequence length andk{\displaystyle k} is the average, over all values in the sequence, of the number of consecutive pairs of sequence values that bracket the given value (meaning that the given value is between the two sequence values). They also prove a lower bound stating that, for anyn{\displaystyle n} and (non-constant)k{\displaystyle k}, any comparison-based sorting algorithm must useΩ(nlogk){\displaystyle \Omega (n\log k)} comparisons for some inputs.[16]

In pattern matching

[edit]

The problem ofCartesian tree matching has been defined as a generalized form ofstring matching in which one seeks asubstring (or in some cases, asubsequence) of a given string that has a Cartesian tree of the same form as a given pattern. Fast algorithms for variations of the problem with a single pattern or multiple patterns have been developed, as well as data structures analogous to thesuffix tree and other text indexing structures.[17]

Notes

[edit]
  1. ^abIn some references, the ordering of the numbers is reversed, so the root node instead holds the maximum value and the tree has the max-heap property rather than the min-heap property.
  2. ^abcVuillemin (1980).
  3. ^abGabow, Bentley & Tarjan (1984).
  4. ^Berkman, Schieber & Vishkin (1993).
  5. ^Shun & Blelloch (2014).
  6. ^Kozma & Saranurak (2020).
  7. ^Hartmann et al. (2021).
  8. ^Bialynicka-Birula & Grossi (2006).
  9. ^Gabow, Bentley & Tarjan (1984);Bender & Farach-Colton (2000).
  10. ^Harel & Tarjan (1984);Schieber & Vishkin (1988).
  11. ^Bender & Farach-Colton (2000).
  12. ^Hu (1961);Leclerc (1981)
  13. ^Demaine, Landau & Weimann (2009).
  14. ^abcSeidel & Aragon (1996).
  15. ^Tarjan, Levy & Timmel (2021).
  16. ^abcLevcopoulos & Petersson (1989).
  17. ^Park et al. (2019);Park et al. (2020);Song et al. (2021);Kim & Cho (2021);Nishimoto et al. (2021);Oizumi et al. (2022)

References

[edit]
Search trees
(dynamic sets,
associative arrays)
Heaps
Tries
Spatial data
partitioning trees
Other trees
Theory
Exchange sorts
Selection sorts
Insertion sorts
Merge sorts
Distribution sorts
Concurrent sorts
Hybrid sorts
Other
Impractical sorts
Retrieved from "https://en.wikipedia.org/w/index.php?title=Cartesian_tree&oldid=1300026915"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp