AlgoMaster Logo

R-Trees

Last Updated: May 26, 2026

Ashish

Ashish Pratap Singh

Medium Priority
8 min read

Many spatial systems need to query objects by shape, such as points, rectangles, lines, and polygons.

An R-tree indexes objects by their minimum bounding rectangles. Queries use those rectangles to skip large parts of the dataset before running exact geometry checks.

R-trees are a strong fit for database-backed spatial queries. Their main trade-off is overlap: when bounding rectangles overlap heavily, a search may need to follow multiple branches.

1. The Problem with Spatial Data

Suppose a food delivery service stores restaurants and delivery zones. Each restaurant has a location, but each delivery zone may be a polygon.

Common queries include:

  • Which restaurants are visible in this map viewport?
  • Which delivery zones contain this customer location?
  • Which stores are within 2 km of this point?
  • Which roads or neighborhoods intersect this polygon?

The brute-force approach checks every object:

This is O(n) per query. With millions of shapes, it is too slow for interactive maps, marketplace search, or high-volume backend APIs.

1.1 Why a B-Tree Is Not Enough

A B-tree can help with one dimension:

That index can narrow a latitude range. It does not understand longitude at the same time, and it does not understand that a polygon overlaps another polygon.

A composite B-tree on (latitude, longitude) can help some bounding-box queries, but it still imposes a one-dimensional sort order. Spatial predicates such as intersects, contains, and nearest need an index that can reason about regions.

1.2 The Bounding Box Pattern

Spatial systems commonly use a two-stage filter:

  1. Use cheap bounding rectangles to find candidates.
  2. Run exact geometry checks on the candidates.

For example, a complex polygon can be wrapped by a simple rectangle:

The rectangle may return false positives, but it should not return false negatives. Exact geometry filtering removes candidates whose bounding boxes overlap but whose actual shapes do not.

R-trees organize those bounding boxes efficiently.

2. What Is an R-Tree?

Premium Content

This content is for premium members only.