Bounding volume hierarchy 2026-10-14
A bounding volume hierarchy is a data structure arranged as a rooted tree: leaves store objects, and each internal node stores a bounding volume enclosing its children in a rooted tree. Consequently, every node encloses all objects in its subtree. A common choice is a binary tree of axis-aligned bounding boxes. The objects assigned to sibling subtrees can be different even when their bounding volumes overlap.[ref]
Here is an exact two-dimensional example. Use the triangles from bounding volume, together with having vertices of a polygon and having vertices of a polygon . Group under , and under . Their parent axis-aligned bounding boxes and the box at the root of a tree are
The diagram shows all seven nodes. Taking the coordinate-wise minimum and maximum of the two child boxes constructs each parent box; the resulting box contains the set union of the children, and can also contain empty space between them.
Figure 1.
Four exact triangles, their enclosing boxes, and a seven-node bounding volume hierarchy arranged as a binary tree
. Details.
A bounding volume hierarchy traversal starts at the root of a tree and discards a subtree when its bounding volume misses the query. Accepted internal nodes expose their children; accepted leaves supply candidates for actual shape tests. Box2D's official Collision: Dynamic Tree describes axis-aligned bounding box region queries that return overlapping leaf boxes. A query box that bounds a different query shape can produce additional false candidates.
For the closed query rectangle
left-first depth-first search tests the node boxes in order: root, , , , . The first four overlap ; does not, because its smallest -coordinate is . Pruning skips both and . Five box tests leave two broad phase candidates. The narrow phase rejects , since throughout , and accepts : the point belongs to both and . There are two detailed shape tests and one true hit.
Figure 2.
An exact rectangle query prunes the right subtree and leaves two box candidates but only one triangle hit
. Details.
For a query asking for all intersections, time complexity depends on the number of visited nodes and the cost of each candidate shape test. With fixed dimension and constant bookkeeping cost per node, the work is
where counts candidate objects and is Big O notation. A balanced binary tree has small height of a binary tree, but a query can enter both children at every level. In this example a query containing visits all seven nodes and tests all four triangles. More generally, a full binary tree with single-object leaves has nodes, so such a query takes work for constant-cost shape tests even when its height of a binary tree is . Listing hits itself requires outputs. Small height alone gives no unconditional logarithmic query bound.
For collision detection between two bounding volume hierarchies, traverse pairs of nodes: reject disjoint pairs of bounding volumes, expand a nonleaf member of an accepted pair, and apply the narrow phase at accepted leaf pairs. A single collection's self-query must exclude pairing an object with itself and avoid duplicate unordered pairs. If every object overlaps every other object, reporting all pairs already requires results. Construction quality, empty space in boxes and the queries determine how much pruning is useful.[ref]
For a short correctness outline, an object is enclosed by its leaf box, and each child box is enclosed by its parent box. Repeated subset relations carry this property to every ancestor. A true query intersection therefore prevents rejection at every ancestor of the object's leaf. Updating leaf boxes after motion also requires restoring all affected ancestor bounds before querying.
Height of a binary tree 2026-10-13
For a nonempty binary tree, the largest number of edges on a downward graph path from its root of a tree to a leaf. A single vertex has height of a binary tree ; a chain of vertices has height of a binary tree . A convenient recursion convention assigns an empty binary tree height , giving for the left and right subtrees. A binary search tree lookup visits at most vertices.
Huffman code 2026-10-14
A Huffman code is the prefix code returned by Huffman coding; the algorithm chooses a code tree, while the code specifies the actual symbol-to-codeword assignment. For the probability distribution in symbol order , the illustrated binary tree gives
The codeword lengths are . This is a prefix code because no complete codeword is an initial segment of another complete codeword. Thus a decoder can start at the root of a tree, follow one edge per bit, emit a symbol on reaching its leaf, then restart at the root of a tree. In particular, 011010111 splits as 0 | 110 | 10 | 111 and decodes to . No separators are transmitted: the leaf tells the decoder where a codeword ends.
The expected codeword length is
bits per source symbol. Four symbols would require bits each if all codewords had the same length, so this Huffman code saves bit per symbol on average, or of that fixed-length payload. A particular message can grow: uses nine bits here instead of eight. These lengths count the encoded symbols only; transmitting a code description or message framing can add further cost.
The Kraft inequality is saturated by this Huffman code:
Its Shannon entropy is
bits per symbol, slightly below the expected codeword length . The entropy lower bound for prefix codes applies to every binary prefix code for this probability distribution. It need not be attainable with integer codeword lengths for individual symbols; Huffman coding reaches the best mean within that class. [ref]
A Huffman code need not be unique. In the first example, the tied and weights can exchange their edge labels, changing codewords but preserving their codeword lengths. Ties can also change the lengths themselves. For a second probability distribution , first merge to weight . The next merge can join with either or the subtree, since both have weight . Joining with permits , with all lengths . Joining with the subtree permits , with lengths . Both are optimal prefix codes with expected codeword length : for the latter, . Tie choices can change the code tree without changing the minimum mean.
// Target: algebra.bigb
Huffman coding Created 2026-09-24 Updated 2026-10-14
Huffman coding makes frequent symbols cheap to store by giving them short codewords, while allowing rare symbols longer codewords. For a known probability distribution on a finite alphabet with at least two positive-probability symbols, binary Huffman coding constructs a prefix code minimizing expected codeword length among binary prefix codes that encode one source symbol at a time. The objective is an average under that probability distribution; it does not promise to shorten every message. Encoder and decoder must agree on the resulting Huffman code. [ref]
The construction grows a binary tree from its leaves towards its root of a tree. Start with one leaf per symbol, weighted by its probability. Repeatedly join the two currently smallest weights beneath a new parent in a rooted tree, whose weight is their sum, and replace the pair by that subtree. Include newly formed subtrees when choosing the next pair. When one tree remains, label the two outgoing edges at every internal vertex with and ; the labels on the graph path from the root of a tree to a symbol give its codeword. This is a greedy algorithm: each step makes a locally cheapest merge, yet the result is an optimal prefix code.
For a concrete example, use probabilities , , , . First join and , creating weight . The remaining weights are for , for the subtree, and for . Join the two weights to make , then join with that subtree to make . The merge weights are therefore . Each merge adds one bit to every codeword below it, so their sum is the expected codeword length: bits per source symbol. The diagram fixes the edge labels to produce the Huffman code used below.
Figure 1.
Huffman merges for probabilities 0.4, 0.3, 0.2, 0.1 and their binary codewords
. Details.
The useful insight is that choosing short codewords is a resource allocation problem: the prefix code condition constrains the available codeword lengths through the Kraft inequality. Huffman coding solves this one-symbol problem exactly for the supplied probability distribution. For repeated emissions of a memoryless classical information source, the same Huffman code can be applied symbol by symbol. More general compression can exploit dependencies or encode groups of symbols; the one-symbol optimality statement does not compare all such methods.
Huffman sibling property Created 2026-09-24 Updated 2026-10-14
For a finite source alphabet of symbols with positive weights , choose any two least weights, breaking ties arbitrarily. There exists an optimal prefix code over the binary output alphabet whose chosen symbols occupy sibling leaves in a code tree at maximum leaf depth in a code tree. Weights may be counts or probabilities: dividing every weight by gives the same minimizers. The existence statement is what makes the first merge of Huffman coding safe. It does not say that every optimal prefix code already has the chosen pair together.[ref]
An exchange makes the idea tangible. Take probabilities . The prefix code , , , has expected codeword length bits. Exchange only the symbols at their existing leaves: the available codewords and code tree shape stay fixed, but the codeword lengths in symbol order become . The new expected codeword length is bits, and the two least probabilities, those of , now occupy deepest sibling leaves in a code tree. The saving is bit per source symbol.
Figure 1.
Exchanging two leaf labels reduces expected length from 2.5 to 1.9 bits; contracting the least-probability siblings leaves cost 1.6
. Details.
Here is the short proof outline. An optimal prefix code with positive weights has a full binary tree as its code tree: suppressing a vertex with only one child shortens every codeword in that subtree and strictly reduces cost. A deepest leaf therefore has a leaf as its sibling, giving the deepest sibling property of an optimal prefix code. Put the two chosen least weights at these positions by successive exchanges of leaf labels. Moving a weight from leaf depth in a code tree to a deepest position , occupied by , changes the weighted sum by
Fix one chosen weight there, then move the other into the neighbouring deepest position; if it is already there, no exchange is needed. The prefix code condition survives because the set of codewords is unchanged. Starting from an optimal prefix code, the cost cannot decrease below the minimum, so these exchanges preserve optimality. Strictly unequal weights at unequal depths would give a strict decrease, explaining probability monotonicity of optimal prefix-code lengths. Equal weights or equal depths allow cost-neutral exchanges. [ref]
Inorder traversal 2026-10-13
An inorder traversal of a binary tree uses recursion to visit the left subtree, output the current vertex, and visit the right subtree; an empty subtree outputs nothing. This is a depth-first traversal of a tree with output between the two recursive calls. It produces sorted keys for a binary search tree, but arbitrary labels in a binary tree need not appear in total order.
// Target: computer-science.bigb
Nonunique optimal prefix code Created 2026-09-24 Updated 2026-09-24
Distinct tree shapes can have the same minimum expected length, particularly when Huffman merges have ties.
Optimal prefix code Created 2026-09-24 Updated 2026-10-14
An optimal prefix code minimizes expected codeword length for a fixed source probability distribution. Here the source alphabet is finite, has symbols, and has for every symbol; each source symbol receives one codeword over the binary output alphabet . Its code tree puts the symbols at leaves. Reading the edges along the graph path from the root of a tree to a leaf produces its codeword, so the leaf depth in a code tree is exactly its codeword length. Thus
For unnormalized positive weights, minimize instead; the corresponding expected codeword length is . This connects the abstract optimization to storage or transmission: counts the bits charged when symbol occurs. Huffman coding attains this minimum; the Huffman sibling property and Huffman sibling contraction explain why. [ref]
For , a balanced code tree charges every symbol two bits, giving . The codeword lengths charge the most frequent symbol only one bit, giving . The choice concerns weighted cost, not just the greatest codeword length: increasing that maximum from two to three can improve the average.
The search over prefix codes looks infinite, but positivity reduces it to finitely many full binary trees with leaves. A vertex with one child can be suppressed to improve cost, and a full binary tree with leaves has internal vertices. There are consequently finitely many such shapes and symbol assignments, so the minimum exists. For four leaves, the only possible sorted codeword lengths in a full binary tree are and . Probability monotonicity of optimal prefix-code lengths assigns larger probabilities to shallower leaves, giving respective minimum costs and in this example. This is an independent small-instance check of the Huffman code.
These hypotheses matter. With zero weights, suppressing a subtree carrying only zero weight need not strictly improve cost, so an optimal prefix code need not have a full binary tree. A one-symbol source raises the convention of whether an empty codeword is allowed. Both cases are outside the original statement here. Encoding groups of symbols changes the source alphabet and the optimization problem; the minimum here concerns one source symbol per codeword.
Subtree 2026-10-13
For a vertex in a rooted tree, its subtree contains and every vertex reachable by repeatedly following children in a rooted tree, together with the connecting edges; its root of a tree is . In a binary tree, the left subtree is rooted at the left child, and is empty when that child is absent; the right subtree is defined similarly. A binary search tree constrains every key in these subtrees.