What is a Quadtree and How Does It Work?
Recursive Subdivision
Start with a bounding box covering all possible points. When a leaf node exceeds capacity (typically 100 to 1000 points), split it into four equal quadrants: NW, NE, SW, SE. Each quadrant becomes a child node. Redistribute points to the appropriate children. Repeat recursively.
Empty quadrants need not be stored. A city with one populated corner has deep subdivisions there but shallow or absent nodes elsewhere. The tree adapts to data density automatically.
Query Algorithm
To find points within a region, start at the root. Check if the query region intersects this node. If not, skip entirely. If yes, check if this is a leaf: search its points. If internal, recursively check children that intersect the query region.
Query complexity depends on tree depth and data distribution. For uniformly distributed data, range queries are O(sqrt(n) + k) where k is result count. For clustered data, performance varies with cluster density. Dense areas have deeper trees and longer traversals.
Insert and Update
Insert traverses from root to the appropriate leaf, then adds the point. If the leaf overflows, split it. Updates for moving points: remove from old location, insert at new location. Frequent moves can cause tree imbalance if not rebalanced periodically.