Trees

A rooted tree organizes nodes hierarchically so every node except the root has exactly one parent—ideal for recursively decomposable hierarchies, while an unrooted tree is a connected acyclic undirected graph.

One-Sentence Definition

A rooted tree organizes nodes into a hierarchy where every node except the root has a single parent—making it ideal for recursively decomposable structures, whereas a general undirected tree is a connected acyclic graph.

Why It Matters

  • Hierarchical data is everywhere: File systems, HTML/DOM documents, JSON payloads, organizational charts, and programming language Abstract Syntax Trees (ASTs) are all trees.
  • Many foundational indexing and ML structures are specialized trees: Binary search trees, heaps, Tries, B-trees (database storage engines), and decision trees / gradient-boosted trees.

Practical Boundaries

Textbooks differ on whether tree depth and height count edges (leaf height = 0) or levels/nodes (leaf height = 1). In our code example below, height() counts levels so a single leaf has height 1. Also remember that once a structure permits shared child nodes, symlinks, or parent back-references, it becomes a directed graph or cyclic graph rather than a strict tree.

How It Works / Diagram

Figure 1
Term Definition
Root The top-level node with no parent
Leaf A terminal node with no children
Depth / Height Depth measures distance from the root down to a node; height measures longest path from a node down to a leaf (counted by levels in our example below, so a leaf has height 1)
Subtree Any node together with all of its descendants

Every tree with nn nodes contains exactly n−1n-1 edges. Because a tree consists of a root connected to zero or more disjoint subtrees, it maps naturally to recursive functions.

Runnable Example

Modeling a project directory tree with a Python dataclass to run recursive pre-order printing, height and leaf counting, and path lookup—then inspecting Python's built-in ast syntax tree and nested JSON objects (verified on Python 3.15.0):

# File: examples/13_tree.py
# Tree: hierarchical acyclic structure underlying file systems, DOM, JSON, and ASTs
from dataclasses import dataclass, field

@dataclass
class TreeNode:
    name: str
    children: list["TreeNode"] = field(default_factory=list)
    def add(self, *kids): self.children.extend(kids); return self

root = TreeNode("project").add(
    TreeNode("src").add(TreeNode("main.py"), TreeNode("utils.py")),
    TreeNode("tests").add(TreeNode("test_main.py")),
    TreeNode("README.md"))

def show(node, prefix=""):                   # Pre-order traversal: visit node before children
    print(prefix + node.name)
    for c in node.children: show(c, prefix + "  ")
show(root)

def height(n): return 1 + max((height(c) for c in n.children), default=0)
def count_leaves(n): return 1 if not n.children else sum(count_leaves(c) for c in n.children)
print("Height:", height(root), "| Leaf count:", count_leaves(root))

def path_to(n, target, path=()):
    path = path + (n.name,)
    if n.name == target: return "/".join(path)
    for c in n.children:
        if (p := path_to(c, target, path)): return p
print("Found path:", path_to(root, "test_main.py"))

# Python source code itself parses into an Abstract Syntax Tree (AST)
import ast
tree = ast.parse("y = (a + b) * 2")
print(ast.dump(tree.body[0].value, indent=1)[:200])

# Parsed JSON documents are also trees
import json
doc = json.loads('{"model": {"name": "x", "layers": [{"type": "attn"}, {"type": "mlp"}]}}')
print("Deep JSON lookup:", doc["model"]["layers"][1]["type"])

Captured output:

project
  src
    main.py
    utils.py
  tests
    test_main.py
  README.md
Height: 3 | Leaf count: 4
Found path: project/tests/test_main.py
BinOp(
 left=BinOp(
  left=Name(id='a'),
  op=Add(),
  right=Name(id='b')),
 op=Mult(),
 right=Constant(value=2))
Deep JSON lookup: mlp

Look at the ast.dump output for (a + b) * 2: the multiplication node Mult() sits at the root while the addition Add() sits in its left subtree—parentheses shape the tree topology, which directly determines evaluation order. See Python's ast module docs: https://docs.python.org/3/library/ast.html

Common Pitfalls

  • Mixing up 0-indexed edge height and 1-indexed level height: Always check whether a problem defines the height of a single-node tree as `0` (edges) or `1` (nodes/levels).
  • Using unguarded recursion on deeply degenerate trees: A skewed tree with 5,000 levels will trip Python's recursion limit (RecursionError; see k2.ds.stack); use an explicit stack or queue for deep trees.
  • Treating a DAG or symlinked directory as a pure tree: Once a node can have two parents or a symbolic link points to an ancestor directory, it is a graph (see k2.ds.graph) and requires a visited set to avoid infinite loops.

Connection to AI Development

  • Decision trees and ensemble models: Random Forests in scikit-learn (see k2.ml.sklearn) and gradient-boosted decision trees in XGBoost and LightGBM.
  • Code intelligence and agent code editing: Static analysis linters, refactoring tools, and repository indexers rely on Python's ast or multi-language tree-sitter parse trees: https://tree-sitter.github.io/tree-sitter/
  • Tree of Thoughts (ToT): Framing multi-step LLM reasoning and lookahead search as tree exploration over candidate thought branches: https://arxiv.org/abs/2305.10601
  • Hierarchical RAG document chunking: Splitting Markdown or HTML documents along their heading tree (`H1 -> H2 -> H3`) so retrieved chunks preserve parent section context.

Further Reading

Concept Check

If a file-system directory contains a symbolic link pointing back to a parent folder, can you traverse it unconditionally with a simple tree recursion?

Reference answer: No—a parent cycle turns the traversal into a cyclic graph walk that will loop until hitting maximum recursion depth unless you skip symlinks or track visited real paths.

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed. Run log: 13_tree.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram