Quadtree
   HOME

TheInfoList



OR:

A quadtree is a
tree data structure In computer science, a tree is a widely used abstract data type that represents a hierarchical tree structure with a set of connected nodes. Each node in the tree can be connected to many children (depending on the type of tree), but must be c ...
in which each internal node has exactly four children. Quadtrees are the two-dimensional analog of
octree An octree is a tree data structure in which each internal node has exactly eight children. Octrees are most often used to partition a three-dimensional space by recursively subdividing it into eight octants. Octrees are the three-dimensional ana ...
s and are most often used to partition a two-dimensional space by recursively subdividing it into four quadrants or regions. The data associated with a leaf cell varies by application, but the leaf cell represents a "unit of interesting spatial information". The subdivided regions may be square or rectangular, or may have arbitrary shapes. This data structure was named a quadtree by
Raphael Finkel Raphael Finkel (born 1951) is an American computer scientist and a professor at the University of Kentucky. He compiled the first version of the Jargon File. He is the author of ''An Operating Systems Vade Mecum'',J.L. Bentley in 1974. A similar partitioning is also known as a ''Q-tree''. All forms of quadtrees share some common features: * They decompose space into adaptable cells * Each cell (or bucket) has a maximum capacity. When maximum capacity is reached, the bucket splits * The tree directory follows the spatial decomposition of the quadtree. A tree-pyramid (T-pyramid) is a "complete" tree; every node of the T-pyramid has four child nodes except leaf nodes; all leaves are on the same level, the level that corresponds to individual pixels in the image. The data in a tree-pyramid can be stored compactly in an array as an
implicit data structure In computer science, an implicit data structure or space-efficient data structure is a data structure that stores very little information other than the main or required data: a data structure that requires low overhead. They are called "implicit" ...
similar to the way a complete binary tree can be stored compactly in an array.


Types

Quadtrees may be classified according to the type of data they represent, including areas, points, lines and curves. Quadtrees may also be classified by whether the shape of the tree is independent of the order in which data is processed. The following are common types of quadtrees.


Region quadtree

The region quadtree represents a partition of space in two dimensions by decomposing the region into four equal quadrants, subquadrants, and so on with each leaf node containing data corresponding to a specific subregion. Each node in the tree either has exactly four children, or has no children (a leaf node). The height of quadtrees that follow this decomposition strategy (i.e. subdividing subquadrants as long as there is interesting data in the subquadrant for which more refinement is desired) is sensitive to and dependent on the spatial distribution of interesting areas in the space being decomposed. The region quadtree is a type of
trie In computer science, a trie, also called digital tree or prefix tree, is a type of ''k''-ary search tree, a tree data structure used for locating specific keys from within a set. These keys are most often strings, with links between nodes ...
. A region quadtree with a depth of n may be used to represent an image consisting of 2n × 2n pixels, where each pixel value is 0 or 1. The root node represents the entire image region. If the pixels in any region are not entirely 0s or 1s, it is subdivided. In this application, each leaf node represents a block of pixels that are all 0s or all 1s. Note the potential savings in terms of space when these trees are used for storing images; images often have many regions of considerable size that have the same colour value throughout. Rather than store a big 2-D array of every pixel in the image, a quadtree can capture the same information potentially many divisive levels higher than the pixel-resolution sized cells that we would otherwise require. The tree resolution and overall size is bounded by the pixel and image sizes. A region quadtree may also be used as a variable resolution representation of a data field. For example, the temperatures in an area may be stored as a quadtree, with each leaf node storing the average temperature over the subregion it represents.


Point quadtree

The point quadtree is an adaptation of a binary tree used to represent two-dimensional point data. It shares the features of all quadtrees but is a true tree as the center of a subdivision is always on a point. It is often very efficient in comparing two-dimensional, ordered data points, usually operating in O(log n) time. Point quadtrees are worth mentioning for completeness, but they have been surpassed by ''k''-d trees as tools for generalized binary search. Point quadtrees are constructed as follows. Given the next point to insert, we find the cell in which it lies and add it to the tree. The new point is added such that the cell that contains it is divided into quadrants by the vertical and horizontal lines that run through the point. Consequently, cells are rectangular but not necessarily square. In these trees, each node contains one of the input points. Since the division of the plane is decided by the order of point-insertion, the tree's height is sensitive to and dependent on insertion order. Inserting in a "bad" order can lead to a tree of height linear in the number of input points (at which point it becomes a linked-list). If the point-set is static, pre-processing can be done to create a tree of balanced height.


Node structure for a point quadtree

A node of a point quadtree is similar to a node of a binary tree, with the major difference being that it has four pointers (one for each quadrant) instead of two ("left" and "right") as in an ordinary binary tree. Also a key is usually decomposed into two parts, referring to x and y coordinates. Therefore, a node contains the following information: * four pointers: quad €˜NW’ quad €˜NE’ quad €˜SW’ and quad €˜SE’* point; which in turn contains: ** key; usually expressed as x, y coordinates ** value; for example a name


Point-region (PR) quadtree

Point-region (PR) quadtrees are very similar to region quadtrees. The difference is the type of information stored about the cells. In a region quadtree, a uniform value is stored that applies to the entire area of the cell of a leaf. The cells of a PR quadtree, however, store a list of points that exist within the cell of a leaf. As mentioned previously, for trees following this decomposition strategy the height depends on the spatial distribution of the points. Like the point quadtree, the PR quadtree may also have a linear height when given a "bad" set.


Edge quadtree

Edge quadtrees (much like PM quadtrees) are used to store lines rather than points. Curves are approximated by subdividing cells to a very fine resolution, specifically until there is a single line segment per cell. Near corners/vertices, edge quadtrees will continue dividing until they reach their maximum level of decomposition. This can result in extremely unbalanced trees which may defeat the purpose of indexing.


Polygonal map (PM) quadtree

The polygonal map quadtree (or PM Quadtree) is a variation of quadtree which is used to store collections of polygons that may be degenerate (meaning that they have isolated vertices or edges). A big difference between PM quadtrees and edge quadtrees is that the cell under consideration is not subdivided if the segments meet at a vertex in the cell. There are three main classes of PM Quadtrees, which vary depending on what information they store within each black node. PM3 quadtrees can store any amount of non-intersecting edges and at most one point. PM2 quadtrees are the same as PM3 quadtrees except that all edges must share the same end point. Finally PM1 quadtrees are similar to PM2, but black nodes can contain a point and its edges or just a set of edges that share a point, but you cannot have a point and a set of edges that do not contain the point.


Compressed quadtrees

This section summarizes a subsection from a book by
Sariel Har-Peled Sariel Har-Peled (born July 14, 1971, in Jerusalem) is an Israeli–American computer scientist known for his research in computational geometry. He is a Donald Biggar Willett Professor in Engineering at the University of Illinois at Urbana–Champ ...
. If we were to store every node corresponding to a subdivided cell, we may end up storing a lot of empty nodes. We can cut down on the size of such sparse trees by only storing subtrees whose leaves have interesting data (i.e. "important subtrees"). We can actually cut down on the size even further. When we only keep important subtrees, the pruning process may leave long paths in the tree where the intermediate nodes have degree two (a link to one parent and one child). It turns out that we only need to store the node u at the beginning of this path (and associate some meta-data with it to represent the removed nodes) and attach the subtree rooted at its end to u. It is still possible for these compressed trees to have a linear height when given "bad" input points. Although we trim a lot of the tree when we perform this compression, it is still possible to achieve logarithmic-time search, insertion, and deletion by taking advantage of ''Z''-order curves. The ''Z''-order curve maps each cell of the full quadtree (and hence even the compressed quadtree) in O(1) time to a one-dimensional line (and maps it back in O(1) time too), creating a total order on the elements. Therefore, we can store the quadtree in a data structure for ordered sets (in which we store the nodes of the tree). We must state a reasonable assumption before we continue: we assume that given two real numbers \alpha, \beta \in Image_processing *_#Mesh_generation_using_quadtrees.html" "title="#Image processing using quadtrees">Image processing * #Mesh generation using quadtrees">Mesh generation Mesh generation is the practice of creating a mesh, a subdivision of a continuous geometric space into discrete geometric and topological cells. Often these cells form a simplicial complex. Usually the cells partition the geometric input domain. ...
* Spatial indexing, point location queries, and range queries * Efficient collision detection in two dimensions * Hidden face removal#Viewing frustum culling, View frustum culling of terrain data * Storing sparse data, such as a formatting information for a
spreadsheet A spreadsheet is a computer application for computation, organization, analysis and storage of data in tabular form. Spreadsheets were developed as computerized analogs of paper accounting worksheets. The program operates on data entered in c ...
or for some matrix calculations * Solution of multidimensional
fields Fields may refer to: Music * Fields (band), an indie rock band formed in 2006 * Fields (progressive rock band), a progressive rock band formed in 1971 * ''Fields'' (album), an LP by Swedish-based indie rock band Junip (2010) * "Fields", a song b ...
(
computational fluid dynamics Computational fluid dynamics (CFD) is a branch of fluid mechanics that uses numerical analysis and data structures to analyze and solve problems that involve fluid flows. Computers are used to perform the calculations required to simulate ...
,
electromagnetism In physics, electromagnetism is an interaction that occurs between particles with electric charge. It is the second-strongest of the four fundamental interactions, after the strong force, and it is the dominant force in the interactions of ...
) *
Conway's Game of Life The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is a zero-player game, meaning that its evolution is determined by its initial state, requiring no furthe ...
simulation program. *
State estimation In control theory, a state observer or state estimator is a system that provides an estimate of the internal state of a given real system, from measurements of the input and output of the real system. It is typically computer-implemented, and pro ...
* Quadtrees are also used in the area of fractal image analysis * Maximum disjoint sets


Image processing using quadtrees

Quadtrees, particularly the
region quadtree In geography, regions, otherwise referred to as zones, lands or territories, are areas that are broadly divided by physical characteristics (physical geography), human impact characteristics (human geography), and the interaction of humanity and t ...
, have lent themselves well to image processing applications. We will limit our discussion to binary image data, though region quadtrees and the image processing operations performed on them are just as suitable for colour images.


Image union / intersection

One of the advantages of using quadtrees for image manipulation is that the set operations of union and intersection can be done simply and quickly. Given two binary images, the image union (also called ''overlay'') produces an image wherein a pixel is black if either of the input images has a black pixel in the same location. That is, a pixel in the output image is white only when the corresponding pixel in ''both'' input images is white, otherwise the output pixel is black. Rather than do the operation pixel by pixel, we can compute the union more efficiently by leveraging the quadtree's ability to represent multiple pixels with a single node. For the purposes of discussion below, if a subtree contains both black and white pixels we will say that the root of that subtree is coloured grey. The algorithm works by traversing the two input quadtrees (T_1 and T_2) while building the output quadtree T. Informally, the algorithm is as follows. Consider the nodes v_1 \in T_1 and v_2 \in T_2 corresponding to the same region in the images. * If v_1 or v_2 is black, the corresponding node is created in T and is colored black. If only one of them is black and the other is gray, the gray node will contain a subtree underneath. This subtree need not be traversed. * If v_1 (respectively, v_2) is white, v_2 (respectively, v_1) and the subtree underneath it (if any) is copied to T . * If both v_1 and v_2 are gray, then the corresponding children of v_1 and v_2 are considered. While this algorithm works, it does not by itself guarantee a minimally sized quadtree. For example, consider the result if we were to union a checkerboard (where every tile is a pixel) of size 2^ \times 2^ with its complement. The result is a giant black square which should be represented by a quadtree with just the root node (coloured black), but instead the algorithm produces a full 4-ary tree of depth k. To fix this, we perform a bottom-up traversal of the resulting quadtree where we check if the four children nodes have the same colour, in which case we replace their parent with a leaf of the same colour. The intersection of two images is almost the same algorithm. One way to think about the intersection of the two images is that we are doing a union with respect to the ''white'' pixels. As such, to perform the intersection we swap the mentions of black and white in the union algorithm.


Connected component labelling

Consider two neighbouring black pixels in a binary image. They are ''adjacent'' if they share a bounding horizontal or vertical edge. In general, two black pixels are ''connected'' if one can be reached from the other by moving only to adjacent pixels (i.e. there is a path of black pixels between them where each consecutive pair is adjacent). Each maximal set of connected black pixels is a ''connected component''. Using the quadtree representation of images, Samet showed how we can find and label these connected components in time proportional to the size of the quadtree. This algorithm can also be used for polygon colouring. The algorithm works in three steps: * establish the adjacency relationships between black pixels * process the equivalence relations from the first step to obtain one unique label for each connected component * label the black pixels with the label associated with their connected component To simplify the discussion, let us assume the children of a node in the quadtree follow the ''Z''-order (SW, NW, SE, NE). Since we can count on this structure, for any cell we know how to navigate the quadtree to find the adjacent cells in the different levels of the hierarchy. Step one is accomplished with a
post-order traversal In computer science, tree traversal (also known as tree search and walking the tree) is a form of graph traversal and refers to the process of visiting (e.g. retrieving, updating, or deleting) each node in a tree data structure, exactly once. ...
of the quadtree. For each black leaf v we look at the node or nodes representing cells that are Northern neighbours and Eastern neighbours (i.e. the Northern and Eastern cells that share edges with the cell of v). Since the tree is organized in ''Z''-order, we have the invariant that the Southern and Western neighbours have already been taken care of and accounted for. Let the Northern or Eastern neighbour currently under consideration be u. If u represents black pixels: * If only one of u or v has a label, assign that label to the other cell * If neither of them have labels, create one and assign it to both of them * If u and v have different labels, record this label equivalence and move on Step two can be accomplished using the
union-find data structure In computer science, a disjoint-set data structure, also called a union–find data structure or merge–find set, is a data structure that stores a collection of disjoint (non-overlapping) sets. Equivalently, it stores a partition of a se ...
. We start with each unique label as a separate set. For every equivalence relation noted in the first step, we union the corresponding sets. Afterwards, each distinct remaining set will be associated with a distinct connected component in the image. Step three performs another post-order traversal. This time, for each black node v we use the union-find's ''find'' operation (with the old label of v) to find and assign v its new label (associated with the connected component of which v is part).


Mesh generation using quadtrees

This section summarizes a chapter from a book by Har-Peled and de Berg et al.
Mesh generation Mesh generation is the practice of creating a mesh, a subdivision of a continuous geometric space into discrete geometric and topological cells. Often these cells form a simplicial complex. Usually the cells partition the geometric input domain. ...
is essentially the triangulation of a point set for which further processing may be performed. As such, it is desirable for the resulting triangulation to have certain properties (like non-uniformity, triangles that are not "too skinny", large triangles in sparse areas and small triangles in dense ones, etc.) to make further processing quicker and less error-prone. Quadtrees built on the point set can be used to create meshes with these desired properties. Consider a leaf of the quadtree and its corresponding cell v. We say v is ''balanced'' (for mesh generation) if the cell's sides are intersected by the corner points of neighbouring cells at most once on each side. This means that the quadtree levels of leaves adjacent to v differ by at most one from the level of v. When this is true for all leaves, we say the whole quadtree is balanced (for mesh generation). Consider the cell v and the 5\times 5 neighbourhood of same-sized cells centred at v. We call this neighbourhood the ''extended cluster''. We say the quadtree is ''well-balanced'' if it is balanced, and for every leaf u that contains a point of the point set, its extended cluster is also in the quadtree and the extended cluster contains no other point of the point set. Creating the mesh is done as follows: # Build a quadtree on the input points. # Ensure the quadtree is balanced. For every leaf, if there is a neighbour that is too large, subdivide the neighbour. This is repeated until the tree is balanced. We also make sure that for a leaf with a point in it, the nodes for each leaf's extended cluster are in the tree. # For every leaf node v that contains a point, if the extended cluster contains another point, we further subdivide the tree and rebalance as necessary. If we needed to subdivide, for each child u of v we ensure the nodes of u's extended cluster are in the tree (and re-balance as required). # Repeat the previous step until the tree is well-balanced. # Transform the quadtree into a triangulation. We consider the corner points of the tree cells as vertices in our triangulation. Before the transformation step we have a bunch of boxes with points in some of them. The transformation step is done in the following manner: for each point, warp the closest corner of its cell to meet it and triangulate the resulting four quadrangles to make "nice" triangles (the interested reader is referred to chapter 12 of Har-Peled for more details on what makes "nice" triangles). The remaining squares are triangulated according to some simple rules. For each regular square (no points within and no corner points in its sides), introduce the diagonal. Note that due to the way in which we separated points with the well-balancing property, no square with a corner intersecting a side is one that was warped. As such, we can triangulate squares with intersecting corners as follows. If there is one intersected side, the square becomes three triangles by adding the long diagonals connecting the intersection with opposite corners. If there are four intersected sides, we split the square in half by adding an edge between two of the four intersections, and then connect these two endpoints to the remaining two intersection points. For the other squares, we introduce a point in the middle and connect it to all four corners of the square as well as each intersection point. At the end of it all, we have a nice triangulated mesh of our point set built from a quadtree.


Pseudocode

The following pseudo code shows one means of implementing a quadtree which handles only points. There are other approaches available.


Prerequisites

It is assumed these structures are used. ''// Simple coordinate object to represent points and vectors'' struct XY ''// Axis-aligned bounding box with half dimension and center'' struct AABB


QuadTree class

This class represents both one quad tree and the node where it is rooted. class QuadTree


Insertion

The following method inserts a point into the appropriate quad of a quadtree, splitting if necessary. class QuadTree


Query range

The following method finds all points contained within a range. class QuadTree


See also

*
Adaptive mesh refinement In numerical analysis, adaptive mesh refinement (AMR) is a method of adapting the accuracy of a solution within certain sensitive or turbulent regions of simulation, dynamically and during the time the solution is being calculated. When solutions ...
*
Binary space partitioning In computer science, binary space partitioning (BSP) is a method for space partitioning which recursively subdivides a Euclidean space into two convex sets by using hyperplanes as partitions. This process of subdividing gives rise to a represen ...
*
Binary tiling In geometry, the binary tiling (sometimes called the Böröczky tiling) is a tiling of the hyperbolic plane, resembling a quadtree over the Poincaré half-plane model of the hyperbolic plane. It was first studied mathematically in 1974 by . How ...
*
Kd-tree In computer science, a ''k''-d tree (short for ''k-dimensional tree'') is a space-partitioning data structure for organizing points in a ''k''-dimensional space. ''k''-d trees are a useful data structure for several applications, such as searc ...
*
Octree An octree is a tree data structure in which each internal node has exactly eight children. Octrees are most often used to partition a three-dimensional space by recursively subdividing it into eight octants. Octrees are the three-dimensional ana ...
* R-tree *
UB-tree The UB-tree as proposed by Rudolf Bayer and Volker Markl is a balanced tree for storing and efficiently retrieving multidimensional data. It is basically a B+ tree A B+ tree is an m-ary tree with a variable but often large number of childre ...
*
Spatial database A spatial database is a general-purpose database (usually a relational database) that has been enhanced to include spatial data that represents objects defined in a geometric space, along with tools for querying and analyzing such data. Most s ...
* Subpaving *
Z-order curve In mathematical analysis and computer science, functions which are Z-order, Lebesgue curve, Morton space-filling curve, Morton order or Morton code map multidimensional data to one dimension while preserving locality of the data points. It i ...


References

Surveys by Aluru and Samet give a nice overview of quadtrees.


Notes


General references

# # Chapter 14: Quadtrees: pp. 291–306. # {{CS-Trees Trees (data structures) Database index techniques Geometric data structures