Quadtrees
A tree where every internal node splits its square into four quadrants, and splits again only where the data is dense — so crowded regions get detail and empty ones cost almost nothing.
Four Children per Square
- Node – owns a square region of 2-D space.
- Children – exactly four or none: NW, NE, SW and SE quadrants of the node's square.
- Leaf – stores up to a fixed number of points, called the capacity (often 1 to 8).
- Split – when a leaf exceeds its capacity it becomes internal, and its points move into the four new children.
- Root – the bounding square of all the data.
A quadtree is a tree data structure for two-dimensional data in which every internal node has exactly four children. Each node represents a square; its children represent the four equal quadrants of that square. It is the 2-D version of a binary search tree's idea — divide the space so a search can ignore most of it — with four-way instead of two-way splits.
The key property is that the tree is adaptive. A uniform grid has to choose one cell size for the whole map, which is too coarse where data crowds and wasteful where it is sparse. It subdivides only the squares that need it, so a map with a dense city and an empty ocean gets many small cells in the city and one large cell for the ocean.
- Four children per internal node, one per quadrant
- Subdivision happens only where the data is dense
- The 3-D version, with eight children, is the octree
- Also written quad tree or Q-tree
Region, Point and PR Variants
Several structures share the name. They differ in where the split happens and what the leaves store, and an exam answer should say which one it means.
The point-region (PR) quadtree used in the tracer is the most common in practice: it splits at the centre and stores points in leaves. The point quadtree is the older form and behaves more like a binary search tree — its shape depends on insertion order, and deleting a point is awkward because the point is also a split.
| Variant | Split at | Leaves store | Typical use |
|---|---|---|---|
| Region quadtree | Centre of the square | A uniform value, such as one colour | Images, terrain, occupancy grids |
| PR (point-region) quadtree | Centre of the square | Up to capacity points | Spatial indexes, collision detection |
| Point quadtree | The stored point itself | One point per node | Textbook multi-key search |
| Edge / polygonal map quadtree | Centre, until each cell is simple | Line segments | Map and CAD geometry |
- Fixed centre splits make region and PR shapes independent of insert order
- The rest of this page means the PR variant unless it says otherwise
Insertion and Range Query
- Insert: find the leaf – starting at the root, move into the one child whose square contains the point.
- Insert: store or split – if the leaf has room, store the point; otherwise split it into four and reinsert its points and the new one.
- Query: test overlap – at each node, if its square does not overlap the query rectangle, return immediately.
- Query: test points – at an overlapping leaf, report the points that lie inside the rectangle.
- Query: recurse – at an overlapping internal node, query all four children.
Insertion only ever follows one path, because the four quadrants do not overlap: a point lies in exactly one of them. Use half-open squares — include the left and bottom edges, exclude the right and top — so a point on a boundary belongs to exactly one child.
A split can cascade. If two points are very close, the first split may put both in the same quadrant, which splits again, and so on until they separate. That is why a PR quadtree needs a maximum depth: two identical points would otherwise split forever.
The range query is where the structure pays off. One overlap test on a large square can discard thousands of points at once, and the query only descends into squares that touch the rectangle.
- Point outside the root square: reject it, or grow a bigger root around the old one
- Deleting a point: remove it, and merge four sibling leaves back into one when they fit in a single leaf
- Moving objects: delete and reinsert, or rebuild the whole tree each frame
Terms, operations, and practical uses
Terms to know
- QuadrantOne of the four equal parts of a node's square: NW, NE, SW or SE.
- CapacityHow many points a leaf may hold before it splits.
- OctreeThe 3-D version: each node splits a cube into eight children.
- Half-open squareIncludes its left and bottom edges only, so boundary points have one home.
Related lessons
- K-d treesBinary splits, one axis at a time, for any dimension.
- TreesNodes, children, depth and height.
- Divide and conquerThe split-into-parts idea a quadtree applies to space.
- RecursionInsert and query both recurse into child quadrants.
Code in Python, C++ and Java
class QuadTree:
CAPACITY = 1
def __init__(self, x, y, size):
self.x, self.y, self.size = x, y, size
self.points = []
self.children = None # [NW, NE, SW, SE] once split
def contains(self, p):
return self.x <= p[0] < self.x + self.size and self.y <= p[1] < self.y + self.size
def insert(self, p):
if not self.contains(p):
return False
if self.children is None:
if len(self.points) < self.CAPACITY:
self.points.append(p)
return True
self.split()
return any(child.insert(p) for child in self.children)
def split(self):
h = self.size / 2
x, y = self.x, self.y
self.children = [
QuadTree(x, y + h, h), # NW
QuadTree(x + h, y + h, h), # NE
QuadTree(x, y, h), # SW
QuadTree(x + h, y, h), # SE
]
for p in self.points:
any(child.insert(p) for child in self.children)
self.points = []
def query(self, x1, y1, x2, y2, found, visited):
# Skip this whole square if it misses the query rectangle.
if x2 < self.x or x1 >= self.x + self.size or y2 < self.y or y1 >= self.y + self.size:
return
visited.append((self.x, self.y, self.size))
for p in self.points:
if x1 <= p[0] <= x2 and y1 <= p[1] <= y2:
found.append(p)
for child in self.children or []:
child.query(x1, y1, x2, y2, found, visited)
def depth(self):
return 0 if self.children is None else 1 + max(c.depth() for c in self.children)
tree = QuadTree(0, 0, 16)
for point in [(3, 13), (12, 12), (5, 4), (6, 6), (13, 3), (10, 6)]:
tree.insert(point)
found, visited = [], []
tree.query(4, 3, 11, 7, found, visited)
print("depth:", tree.depth())
print("points in [4,11] x [3,7]:", " ".join(f"({x}, {y})" for x, y in sorted(found)))
print("squares visited:", len(visited))#include <algorithm>
#include <array>
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
struct Point {
double x, y;
};
class QuadTree {
public:
QuadTree(double x, double y, double size) : x_(x), y_(y), size_(size) {}
bool insert(const Point& p) {
if (!contains(p)) return false;
if (!children_[0]) {
if (points_.size() < kCapacity) {
points_.push_back(p);
return true;
}
split();
}
for (auto& child : children_) {
if (child->insert(p)) return true;
}
return false;
}
void query(double x1, double y1, double x2, double y2, vector<Point>& found, int& visited) const {
// Skip this whole square if it misses the query rectangle.
if (x2 < x_ || x1 >= x_ + size_ || y2 < y_ || y1 >= y_ + size_) return;
visited++;
for (const Point& p : points_) {
if (x1 <= p.x && p.x <= x2 && y1 <= p.y && p.y <= y2) found.push_back(p);
}
if (!children_[0]) return;
for (const auto& child : children_) child->query(x1, y1, x2, y2, found, visited);
}
int depth() const {
if (!children_[0]) return 0;
int deepest = 0;
for (const auto& child : children_) deepest = max(deepest, child->depth());
return 1 + deepest;
}
private:
static constexpr size_t kCapacity = 1;
double x_, y_, size_;
vector<Point> points_;
array<unique_ptr<QuadTree>, 4> children_; // NW, NE, SW, SE once split
bool contains(const Point& p) const {
return x_ <= p.x && p.x < x_ + size_ && y_ <= p.y && p.y < y_ + size_;
}
void split() {
double h = size_ / 2;
children_[0] = make_unique<QuadTree>(x_, y_ + h, h);
children_[1] = make_unique<QuadTree>(x_ + h, y_ + h, h);
children_[2] = make_unique<QuadTree>(x_, y_, h);
children_[3] = make_unique<QuadTree>(x_ + h, y_, h);
for (const Point& p : points_) {
for (auto& child : children_) {
if (child->insert(p)) break;
}
}
points_.clear();
}
};
int main() {
QuadTree tree(0, 0, 16);
vector<Point> points = {{3, 13}, {12, 12}, {5, 4}, {6, 6}, {13, 3}, {10, 6}};
for (const Point& p : points) tree.insert(p);
vector<Point> found;
int visited = 0;
tree.query(4, 3, 11, 7, found, visited);
sort(found.begin(), found.end(),
[](const Point& a, const Point& b) { return a.x < b.x || (a.x == b.x && a.y < b.y); });
cout << "depth: " << tree.depth() << "\n";
cout << "points in [4,11] x [3,7]:";
for (const Point& p : found) cout << " (" << p.x << ", " << p.y << ")";
cout << "\nsquares visited: " << visited << "\n";
return 0;
}import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
record Point(double x, double y) {}
static class QuadTree {
static final int CAPACITY = 1;
final double x, y, size;
final List<Point> points = new ArrayList<>();
QuadTree[] children; // NW, NE, SW, SE once split
QuadTree(double x, double y, double size) {
this.x = x;
this.y = y;
this.size = size;
}
boolean contains(Point p) {
return x <= p.x() && p.x() < x + size && y <= p.y() && p.y() < y + size;
}
boolean insert(Point p) {
if (!contains(p)) return false;
if (children == null) {
if (points.size() < CAPACITY) {
points.add(p);
return true;
}
split();
}
for (QuadTree child : children) {
if (child.insert(p)) return true;
}
return false;
}
void split() {
double h = size / 2;
children = new QuadTree[] {
new QuadTree(x, y + h, h), new QuadTree(x + h, y + h, h),
new QuadTree(x, y, h), new QuadTree(x + h, y, h)
};
for (Point p : points) {
for (QuadTree child : children) {
if (child.insert(p)) break;
}
}
points.clear();
}
int query(double x1, double y1, double x2, double y2, List<Point> found) {
// Skip this whole square if it misses the query rectangle.
if (x2 < x || x1 >= x + size || y2 < y || y1 >= y + size) return 0;
int visited = 1;
for (Point p : points) {
if (x1 <= p.x() && p.x() <= x2 && y1 <= p.y() && p.y() <= y2) found.add(p);
}
if (children != null) {
for (QuadTree child : children) visited += child.query(x1, y1, x2, y2, found);
}
return visited;
}
int depth() {
if (children == null) return 0;
int deepest = 0;
for (QuadTree child : children) deepest = Math.max(deepest, child.depth());
return 1 + deepest;
}
}
public static void main(String[] args) {
QuadTree tree = new QuadTree(0, 0, 16);
double[][] points = {{3, 13}, {12, 12}, {5, 4}, {6, 6}, {13, 3}, {10, 6}};
for (double[] p : points) tree.insert(new Point(p[0], p[1]));
List<Point> found = new ArrayList<>();
int visited = tree.query(4, 3, 11, 7, found);
found.sort(Comparator.comparingDouble(Point::x).thenComparingDouble(Point::y));
System.out.println("depth: " + tree.depth());
StringBuilder line = new StringBuilder("points in [4,11] x [3,7]:");
for (Point p : found) line.append(String.format(" (%.0f, %.0f)", p.x(), p.y()));
System.out.println(line);
System.out.println("squares visited: " + visited);
}
}Step through it
Running on A(3,13) B(12,12) C(5,4) D(6,6) E(13,3) F(10,6); box x 4–11, y 3–7
Depth, Time and Space
The height is not bounded by the number of points but by how close they are. For a PR quadtree over a square of side s, whose closest pair of points is d apart, the depth is at most log₂(s / d) + 3/2: each level halves the side, and two points d apart cannot share a square whose diagonal is shorter than d. Well-spread points give a depth near log₄ n; a tight cluster can give a deep, narrow tree even for few points.
- Insert and point search: O(h), one root-to-leaf path (an insert may add a cascade of splits)
- Range query: O(h + k) plus the squares that touch the rectangle, for k points reported
- Build: O(n · h) for n inserts
- Space: O(n · h) in the worst case, O(n) for well-spread points
Where It Is Used
Collision detection in games is the classic use. Checking every pair of n objects costs O(n²); putting them in the tree means each object only tests the objects in its own and neighbouring leaves. Maps and GIS index points of interest by location, so a "what is near me" query opens only nearby squares — web map tiles are addressed with the same four-way split.
A region quadtree compresses images: a quadrant that is one colour becomes a single leaf, so large flat areas cost almost nothing. The Barnes–Hut simulation uses a quadtree (or octree in 3-D) to treat a distant cluster of bodies as one mass, cutting an n-body step from O(n²) to O(n log n).
| Quadtree | K-d tree | |
|---|---|---|
| Children | 4 (2-D only; octree for 3-D) | 2, in any dimension |
| Split | Both axes at once | One axis per level |
| Shape | Follows point density | Balanced by median build |
| Updates | Easy: split or merge one leaf | Rebuild to rebalance |
| Best for | Moving objects, images, uneven 2-D data | Static points, nearest neighbour |
- Pick a k-d tree for static points in more than two dimensions
- Pick this structure when objects move every frame or density is very uneven