Collecting the Leaves of a Tree

To collect leaves in order, emit the current node if it has no children. Otherwise traverse its children in their declared order.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a nested set of folders
  2. Avoid repeated concatenation
  3. Preserve leaf order while removing internal structure
  4. Make the difference between an empty group and a leaf explicit

Trace a nested set of folders

A root with leaves A and C and one internal B between them can emit A, B's leaves, and C. If B has D and E, the final sequence is A, D, E, C. Tree traversal order determines the order of those visits.

Avoid repeated concatenation

Returning a separate full list from each node and repeatedly copying its contents can add work on deep trees. Yield leaves or append to a shared output under a clear mutation contract when the space and interface call for it.[1]

Preserve leaf order while removing internal structure

Suppose a document group A contains leaves p and q, followed by group B containing r. A left-to-right flattening produces p, q, r. Neither group label belongs in that output. To locate a leaf later, emit its path or keep it alongside the value. See flattening nested sequences.

Root
  A
    p
    q
  B
    r
Flattened values: p, q, r
Optional leaf paths: A/p, A/q, B/r

Make the difference between an empty group and a leaf explicit

A group with no children can represent an empty collection. Treating every childless object as a leaf would emit that group incorrectly if the model distinguishes group and leaf by kind. Include an empty group before a real leaf in a test and check order and output count.

References

  1. Jeff Erickson, Algorithms ↩