CSE3144 · Advanced Data Structures · Jul–Nov Semester 2026 · Lecture 24 of 36 · CO CSE3144.4

Quad Trees and Oct Trees

Lecture 22 built a quadtree. Today: the two operations it deferred — finding a region's neighbor without a parent pointer, and repairing a tree that's grown lopsided — plus the full 3D generalization, the octree, built and searched from scratch.

Dr. Manu ShrivastavaCourse Instructor · Consultation Fri 2–5 PM, LHC 308F
~181 minutesSession outcome: analyze spatial partitioning in 2D and 3D spaces
L24 · 00 — Agenda ~181 min

One more dimension, and two operations 2D alone couldn't finish

Recap & extending the tree

00–10

Lecture 22's 5-point quadtree, plus two more points that will matter today.

Quadtree properties

10–18

Why quadtrees get lopsided, and the depth/side-length relationship behind it.

Neighbor-finding — concept & animation

18–50

No parent pointer stored — so finding "what's north of me" means climbing, then descending.

Why mesh generation needs balance

50–58

A heat-flow example motivates why simulation needs a mesh at all, then the T-junction problem, then what balancing actually guarantees (bounds it, does not remove it).

The general algorithm

58–66

Climb, then Open Up — the full rule, including the coordinate check the earlier rules skip.

Worked example: every case

66–91

One purpose-built tree, one query, every rule firing at least once — including OpenUp branching twice in a row.

Balancing — concept & animation

91–113

Fixing the exact imbalance neighbor-finding just exposed, then re-verifying it.

Octrees — concept

113–123

Same idea, one more axis: 8 octants instead of 4 quadrants.

Animation: octree INSERT

123–143

Five 3D points, one genuine collision, resolved by subdividing.

Animation: octree SEARCH

143–158

Three queries: found directly, not found, found by recursing.

Complexity, applications & recap

158–181

What each operation costs, where this runs, and what's next.

CSE3144 — Lecture 24
L24 · 01 — Recap & extending the tree ~10 min

Two more points, to set up today's story

Quick recap from Lecture 22
  • A quadtree splits a square into 4 fixed quadrants (NW, NE, SE, SW) whenever a cell holds more than 1 point — the split point is always the cell's geometric midpoint, never a data point.
  • Lecture 22 built a 5-point tree: A(15,15), B(25,60), C(65,20), D(70,65), E(20,20) on an 80×80 square, with the SW quadrant needing one extra level of splitting.
Adding G(5,25) and H(12,35)

Both points land inside the NW quadrant's territory. Watch what happens when the second one arrives.

Interactive — extending the tree with 2 more points
CSE3144 — Lecture 24 · Extending the tree
L24 · 02 — Quadtree properties ~8 min

Why quadtrees get lopsided, made precise

Side lengths halve with depth

Every split cuts a cell's side length in half. A cell at depth d has side length s/2d, where s is the root's side length. Depth grows only where points are close together.

The depth bound

If c is the smallest distance between any two points and s is the root square's side length, the tree's depth is at most log(s/c) + 3/2. A tightly clustered pair of points (small c) can force many extra levels — exactly what we're about to see with G and H.

The direct consequence: two quadrants that are geometrically right next to each other can end up at very different depths — one a single quick split, its neighbor five levels deep. That mismatch is precisely what "unbalanced" means, and it's what today's two operations have to deal with.

CSE3144 — Lecture 24 · Quadtree properties
L24 · 03 — Neighbor-finding — concept ~10 min

No parent pointer needed — but no parent pointer STORED either

The query

Given a node v (a square region) and a direction (say, north), find the node adjacent to v in that direction. This is the operation mesh-generation and rendering algorithms call constantly — "what's the region right next to this one?"

The algorithm (north neighbor)
  • If v is a south child (SW or SE) of its parent: the answer is simply the corresponding sibling directly above it (SW→NW, SE→NE) — no climbing needed.
  • If v is a north child (NW or NE): first recursively find the north neighbor of v's parent (climb up).
  • If that climb returns a leaf (or nothing): that leaf IS the answer, even if it's a different size than v.
  • If that climb returns an internal node: descend into its corresponding south child (NW→SW, NE→SE) to land at the right position.

Running time: O(d+1) in a tree of depth d — one climb up, at most one matching descend down. The same logic (mirrored) finds south, east, and west neighbors.

CSE3144 — Lecture 24 · Neighbor-finding concept
L24 · 04 — SW’s four neighbours: two easy, two hard ~4 min

Neighbour is always directional — a cell has up to 4 of them, not one

Reading the diagram
  • SW (highlighted) is both a south child and a west child of its parent — every cell is exactly one of {north, south} × one of {east, west}.
  • North & east (solid, teal): both land on a sibling inside the same parent square — NorthNeighbor(SW)=NW, EastNeighbor(SW)=SE. No climbing: the algorithm’s trivial case.
  • South & west (dashed, orange): both would land outside the parent square entirely — there is no sibling to point to. This is exactly when the algorithm must climb to the parent first, then descend back down on the other side.
  • Which two directions are “easy” depends on the quadrant: NE’s easy pair is south & west; SW’s is north & east — always the two directions pointing INTO the square, never the two pointing out of it.
In a picture NW sibling NE SW query cell SE sibling the parent square SW belongs to N → NW E → SE S: outside → climb W: outside → climb
CSE3144 — Lecture 24 · Neighbour-finding, visualised
L24 · 05 — Animation: neighbor-finding ~28 min

Three queries — sibling, deep climb, and a genuine descend

First the easy case (a direct sibling), then a genuine 3-level climb that reveals today's tree is unbalanced — then a third query, on a different small tree, built specifically to trigger the one rule the first two never do: climbing up and finding an INTERNAL node to descend back into.

Interactive — north-neighbor queries on the extended tree
CSE3144 — Lecture 24 · Neighbor-finding
L24 · 06 — Why mesh generation needs balance: the T-junction problem ~8 min

Balancing bounds the damage — it does not remove it

Why you need a mesh at all

Say you want to simulate heat spreading across a metal plate. The plate is continuous — every one of its infinitely many points has its own temperature. A computer can’t store or compute on infinitely many points, so you chop the plate into a finite grid of small squares (or triangles) and only track temperature at their corners. Each small piece is an element; each tracked corner is a node; the whole chopped-up grid is the mesh. Here, each quadtree leaf cell becomes one mesh element.

The T-junction problem

Simulation math (and clean rendering) assumes neighboring elements share a boundary completely — corner to corner. A T-junction is a corner of a small cell landing in the middle of a bigger cell’s edge, where the bigger cell has no matching corner: a hanging node.

Before vs. after — today’s own tree BEFORE BALANCING NW depth 1 — ONE edge ∅ d3 H d3 G d3 ∅ d3 E SW-NE, d2 hang hang 2 hanging nodes on ONE edge AFTER BALANCING B NW-NW, d2 ∅ NW-NE, d2 ∅ NW-SW, d2 ∅ NW-SE, d2 ∅ d3 H d3 G d3 ∅ d3 E SW-NE, d2 hang matched 1 hanging node — the OTHER edge now matches

Before: NW (depth 1) is ONE flat edge sitting above three smaller cells of two different depths — TWO hanging nodes on that one edge. Balancing splits NW once. Now NW-SE lines up exactly with SW-NE (a clean, matched corner) — but NW-SW still sits above two depth-3 cells, so ONE hanging node remains.

What balancing actually guarantees

Balancing does not eliminate T-junctions. It guarantees every edge has at most one hanging node, never two or more, never arbitrarily nested. That single, fixed, always-the-same-shape case is what every mesh generator, renderer, and collision routine is already written to patch — an unbounded number of hanging nodes per edge is what they can’t handle.

CSE3144 — Lecture 24 · Mesh generation & the T-junction problem
L24 · 07 — The general algorithm ~8 min

Climb, then Open Up — rules 1–4 are only half of it

Phase 1 — Climb (what Sections 03–05 already covered)
NorthNeighbor(v):
    R = Climb(v)
    # leaf/boundary: done (1-3)
    if R is null or R is a leaf:
        return [R]
    # still internal: not done yet
    return OpenUp(R, v.x0, v.x1)


Climb(v):   # rules 1-4
  if v is a south child:
    return sibling above  # rule 1
  R = Climb(v.parent)  # rule 2
  if R is null or leaf:
    return R  # rule 3
  return R's matching child
            # rule 4: NW->SW, NE->SE
            # safe: v, parent always
            # exactly one level apart

Every example so far (Query 1, Query 2, the balancing re-verify) stopped here: the climb always landed on a leaf or returned to the root. One climb up, at most one matching descend down — genuinely O(d+1).

Phase 2 — Open Up (what Query 3 hinted at)
OpenUp(R, vx0, vx1):
  # what rules 1-4 skip entirely
  if R is a leaf:
    return [R]
  found = []
  for child in [R.SW, R.SE]:
    # R's 2 south-facing children
    if child.x-range
         overlaps [vx0, vx1]:
      found += OpenUp(child,
                       vx0, vx1)
      # recurse: may branch again
  return found

Climb can return a node that is still internal — coarser than v, but not down to leaf level. Rule 4 only ever descends ONE level using v’s own NW/NE label. OpenUp keeps going, using actual coordinates instead of a label, until every branch bottoms out at a leaf.

Why rule 4’s label trick stops working

Rule 4 compares v’s NW/NE label to decide which child of R to take — and that is only safe when R and v are exactly one depth level apart, because then v’s own extent can never straddle R’s upcoming split. The moment R is more than one level coarser than v, that guarantee is gone: v’s extent can straddle the split, and the label alone can’t tell you that. OpenUp checks the real coordinates instead, which is why it can correctly return one leaf, several leaves, or recurse several levels deep — whatever the tree actually looks like.

On a balanced tree, Climb’s result is always already a leaf — OpenUp is called but returns immediately, every time. That is the entire payoff of balancing: Phase 2 becomes dead code in practice. The next slide builds a tree where it isn’t.

CSE3144 — Lecture 24 · The general neighbor-finding algorithm
L24 · 08 — Worked example: every case, including OpenUp ~25 min

One tree, three queries, every rule fires at least once

A fresh tree, built on purpose so nothing is left to chance: rule 1 alone, then rule 2 + rule 1 + rule 3, then the full chain ending in OpenUp branching twice in a row. Every recursive call is its own step.

Interactive — Query A (trivial) → Query B (climb + leaf) → Query C (the full OpenUp cascade)
CSE3144 — Lecture 24 · The general algorithm, fully worked
L24 · 09 — Balancing — concept ~8 min

Neighbors may differ in depth by at most 1

The definition

A quadtree is balanced if every pair of adjacent (neighboring) leaf cells differs by at most 1 in depth. Our extended tree just failed this test by a depth difference of 2.

The fix

Balancing repeatedly finds any leaf whose region needs splitting to satisfy the ≤1 rule, splits it, and then checks whether that NEW split creates any further violations among ITS neighbors too (a worklist that keeps growing if needed) — until no violations remain.

Why bother? Balanced quadtrees are exactly what mesh generation needs for well-shaped triangles, and what many rendering/collision algorithms assume when they compare neighboring cells directly. A balanced quadtree with m nodes stays O(m) in size — balancing doesn't blow up the tree, it just closes the worst gaps.

CSE3144 — Lecture 24 · Balancing concept
L24 · 10 — Animation: balancing ~22 min

Fixing the exact violation we just found

One corrective split, verified to cause no further violations — then we re-run the SAME neighbor query from before and watch the algorithm's descend step finally get exercised.

Interactive — balancing the extended tree
CSE3144 — Lecture 24 · Balancing
L24 · 11 — Octrees — concept ~10 min

Same idea, one more axis: 8 octants instead of 4 quadrants

The generalization

An octree partitions a CUBE instead of a square. Every internal node has exactly 8 children, one per octant, formed by comparing a point's (x,y,z) against the cube's midpoint on all three axes at once. Used for 3D point clouds, volumetric graphics, and 3D collision detection.

The 8 octants

Named by comparing each coordinate to the cube's midpoint: Left/Right (x), Top/Bottom (y), Front/Back (z).

TopLeftFrontx≤mid, y≤mid, z≤mid
TopRightFrontx>mid, y≤mid, z≤mid
BottomRightFrontx>mid, y>mid, z≤mid
BottomLeftFrontx≤mid, y>mid, z≤mid
TopLeftBottomx≤mid, y≤mid, z>mid
TopRightBottomx>mid, y≤mid, z>mid
BottomRightBackx>mid, y>mid, z>mid
BottomLeftBackx≤mid, y>mid, z>mid
INSERT and SEARCH, in one sentence each

INSERT: descend by comparing (x,y,z) to the current cube's midpoint on all 3 axes; if the target octant is empty, place the point; if it already holds a DIFFERENT point, subdivide that octant into its own 8 octants and re-insert both points; if it's already internal, recurse. SEARCH: same descent, but stop as soon as you hit an empty octant (not found) or a point that matches exactly (found).

CSE3144 — Lecture 24 · Octree concept
L24 · 12 — Animation: octree INSERT ~20 min

5 points into an 80×80×80 cube

P1(20,20,20), P2(60,60,60), P3(20,60,20), P4(60,20,60), P5(25,25,25) — the last one collides with the first, forcing a real subdivision.

Interactive — octree INSERT, 5 points
CSE3144 — Lecture 24 · Octree INSERT
L24 · 13 — Animation: octree SEARCH ~15 min

Three queries: found, not found, found-by-recursing

Interactive — octree SEARCH, 3 queries
CSE3144 — Lecture 24 · Octree SEARCH
L24 · 14 — Complexity, applications & recap ~23 min

What each operation costs, and where this runs

OperationQuadtree (2D)Octree (3D)
INSERT / SEARCHO(d) where d = depthO(log N) typical (per node visited, N = point count)
NEIGHBOR-FINDINGO(d+1)Same recursive climb-and-descend idea, one more axis
BALANCING (m nodes)O(m) nodes in the result, O((d+1)·m) time to build itAnalogous, rarely needed in practice for point-cloud use cases
Nodes for n points, depth dO((d+1)·n)O((d+1)·n), branching factor 8 instead of 4
Mesh generation

Balanced quadtrees produce the well-shaped, non-uniform triangular meshes finite-element simulations need — today's whole reason balancing exists.

3D graphics & point clouds

Octrees compress sparse 3D data (LIDAR scans, voxel models) by collapsing empty regions to single leaves, exactly like quadtree image compression in 2D.

Collision detection

Both structures let a game or physics engine skip whole empty regions instead of checking every pair of objects — 2D for top-down games, 3D octrees for full 3D scenes.

Lecture 25 — next

BSP Trees (Binary Space Partitioning Trees)

CO CSE3144.4 — the generalization that drops the axis-aligned restriction entirely: splitting planes at any orientation.

Homework — bring to Lecture 25
  • On today's BALANCED tree, find the WEST neighbor of SW-NE (holding E). Show every climb/descend step, mirroring the north-neighbor algorithm.
  • Insert one more 3D point, (35,35,35), into today's final octree. Show which octant it lands in and whether it triggers a further subdivision.
  • In 3–4 sentences: why does an octree's branching factor of 8 (vs. a quadtree's 4) mean the SAME point-clustering problem gets worse, not better, in 3D?
CSE3144 — Lecture 24

Questions?

Dr. Manu Shrivastava — LHC 308F — Friday 2:00–5:00 PM

Next: Lecture 25 — BSP Trees (Binary Space Partitioning Trees).