Quadtrees

Splitting the map in 4 · Part of Reliability and security

Key idea

Practice

6 questions · about 3 min

Explained step by step

Quadtree

A quadtree is a tree-shaped data structure where each internal node has exactly 4 children. It's used to split a 2-dimensional space, like a map, into 4 quadrants, and each quadrant into 4 more, again and again. Each leaf (a node without children) stores the points in its area. It's like folding a map in 4, and each part again in 4, until each piece holds few things.

The quadtree starts with 1 node covering the whole map. When an area has too many points, it's split into 4 quadrants, and each becomes a child. If a child fills up too, it's split again. That way, areas with many points (a city) end up divided into tiny cells and empty ones (the ocean) stay as 1 big cell. It's like placing mailboxes: a building has 100, the countryside 1 per kilometer.

To save computation, a node is split only after it passes a threshold, for example 100 points. That way no cells are created for almost empty areas. Also, with algorithms like the Hilbert curve, which orders cells so nearby ones stay together, area searches get even faster. It's like opening a new box only when the previous one is full: you don't have 50 empty boxes taking up space.

There are several kinds of quadtree depending on what they store: areas, points, lines or curves. The common ones are: point quadtree, point-region (PR) quadtree, polygonal map (PM) quadtree, compressed quadtree and edge quadtree. Their 3-dimensional cousin is the octree, where each node has 8 children. It's like moving boxes: depending on whether you pack books, clothes or plates, you use a different box.

Quadtrees are used to represent, process and compress images, for spatial indexes and area searches, for location services like Google Maps and Uber, for computer graphics and for storing sparse data. At Uber, for example, they help find the cars near a rider. It's like a library catalog: it takes you straight to the right spot instead of walking through everything.

Euclidean distance

With latitude and longitude you can compute how close 2 points are with the euclidean distance, the straight-line distance. But doing it against millions of points uses a huge amount of CPU and doesn't scale. The quadtree lets you search points within an area without looking at the rest: you go down the tree to the user's cell and check only those points. It's like finding a book by going straight to the right shelf instead of checking the library's 100,000.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Splitting the map in 4