Programming Search⌘K

Conceptintro

Tree

Also called tree, tree data structure, rooted tree, node tree, parent and child nodes, hierarchy.

A tree is a set of nodes where each node has one parent, except the root, and any number of children. File systems, the DOM, syntax trees and menus are trees.

Applies to
core-languages

Idea

A tree stores items in a hierarchy. Each item is a node. A node can have children, and each child has exactly one parent. The one node with no parent is the root. Wikipedia: "Each node in the tree can be connected to many children (depending on the type of tree), but must be connected to exactly one parent".1

A folder of files is a tree. This program builds one from nodes that hold a list of children, prints it, and adds up the sizes.

from dataclasses import dataclass, field


@dataclass
class Node:
    name: str
    size: int = 0
    children: list = field(default_factory=list)


def show(node, depth=0):
    label = node.name + "/" if node.children else node.name
    print("  " * depth + label)
    for child in node.children:
        show(child, depth + 1)


def total_size(node):
    return node.size + sum(total_size(child) for child in node.children)


root = Node("project", children=[
    Node("README.md", 120),
    Node("src", children=[Node("main.py", 300), Node("util.py", 80)]),
    Node("tests", children=[Node("test_main.py", 150)]),
])
show(root)
print("total size:", total_size(root))
Output
project/
  README.md
  src/
    main.py
    util.py
  tests/
    test_main.py
total size: 650

Both functions call themselves on each child. Each child is the root of a smaller tree, so recursion fits the shape.

How it works

Words. The root is the top node. A node with no children is a leaf. The depth of a node is the length of the path from the root to it. Wikipedia: "The height of a node is the length of the longest downward path to a leaf from that node."1 Nodes with the same parent are siblings. Each node and all the nodes below it form a subtree.1

No cycles. Because each node has one parent, no node can be below itself. Wikipedia: "These constraints mean there are no cycles". Each child is also the root of its own subtree, "making recursion a useful technique for tree traversal."1

How programs store a tree.

  • A node object holds its data and a list of its children. This is the most common form. Wikipedia: "In working memory, nodes are typically dynamically allocated records with pointers to their children, their parents, or both".1
  • A node holds a pointer to its first child and a pointer to its next sibling. Each node then has the same fixed size.
  • A table holds one row per node, with the id of the parent. "In relational databases, nodes are typically represented as table rows, with indexed row IDs facilitating pointers between parents and children."1
  • An array holds the nodes at fixed positions. A binary heap stores a complete binary tree like this.1 See priority-queue.

A parent pointer makes it fast to go up from a node to the root. Without it, a program must search from the root to find the parent of a node.

Walks. A program visits every node with a walk.1

  • Pre-order: "each parent node is traversed before its children".1 The Idea example prints in pre-order.
  • Post-order: "the children are traversed before their respective parents".1 The size total needs the children first.
  • Level-order: the root, then its children, then their children. This walk uses a queue. See queue-concept.

The walk algorithms and their proofs are on the algorithm site: tree traversal, binary search tree.

Where trees appear. Wikipedia lists file systems, class hierarchies, abstract syntax trees, and the DOM trees of XML and HTML documents.1 MDN: "The DOM represents a document with a logical tree."2

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaIdiom
CIdiom
C#Idiom
JavaScriptIdiom
TypeScriptIdiomA recursive interface with a children array describes a node, as in the JavaScript example. No example file exists.
GoIdiom
RustIdiom
KotlinIdiomA data class with a List of children is a node. No example file exists because kotlinc is not installed.
SQLIdiomA table with a parent id column stores a tree, one row per node. A recursive query walks it.
BashDoes not applyBash has no nested data structures. The file system itself is a tree, and find walks it.
PowerShellIdiomNested hashtables or custom objects with a children array form a tree. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no data structures for a program. Its nested elements form the DOM tree that scripts walk.
CSSDoes not applyCSS style rules have no data structures. Selectors match elements by their place in the DOM tree.
Regular expressionsDoes not applyA regular expression matches text. It has no data structures.

No core language has a general tree type in its standard library. A program declares a node type with a list of children. Some libraries give trees for one purpose.

Language Verdict Form
Python idiom a class with a children list; ast for syntax trees3
JavaScript idiom objects with a children array; the DOM Node in browsers4
TypeScript idiom a recursive interface with children: Node[]
Java idiom a class with a List of children
C idiom a struct with child pointers, or first-child and next-sibling pointers
C++ idiom a struct with a std::vector of children
C# idiom a class with a List<T> of children
Go idiom a struct with a slice of child pointers
Rust idiom a struct with a Vec of children
Kotlin idiom a data class with a List of children
PowerShell idiom nested hashtables or custom objects
Bash n/a no nested data; the file system is a tree that find walks
SQL idiom a table with a parent id column1
Regex n/a a pattern has no data structures
HTML/CSS n/a nested elements form the DOM tree, which scripts walk2

Python. "The ast module helps Python applications to process trees of the Python abstract syntax grammar."3 ast.walk will "Recursively yield all descendant nodes in the tree starting at node (including node itself), in no specified order."3 For folders, Path.walk will "Generate the file names in a directory tree by walking the tree either top-down or bottom-up."5

JavaScript. In a browser, each DOM node has childNodes, which "Returns a live NodeList containing all the children of this node".4 parentNode "Returns a Node that is the parent of this node."4

Java and Rust. TreeMap is "A Red-Black tree based NavigableMap implementation."6 Rust has BTreeMap and BTreeSet among its maps and sets.7 These types use a tree inside, but they are sorted maps and sets. A program cannot see or walk their nodes. See ordered-map.

The example files build the same folder tree in each language. They print it, count the files, add up the sizes and find the height.

PythonGitHub
from dataclasses import dataclass, field


@dataclass
class Node:
    name: str
    size: int = 0
    children: list = field(default_factory=list)


def show(node, depth=0):
    indent = "  " * depth
    if node.children:
        print(f"{indent}{node.name}/")
        for child in node.children:
            show(child, depth + 1)
    else:
        print(f"{indent}{node.name} {node.size}")


def count_files(node):
    if not node.children:
        return 1
    return sum(count_files(child) for child in node.children)


def total_size(node):
    return node.size + sum(total_size(child) for child in node.children)


def height(node):
    return max((1 + height(child) for child in node.children), default=0)


root = Node("project", children=[
    Node("README.md", 120),
    Node("src", children=[Node("main.py", 300), Node("util.py", 80)]),
    Node("tests", children=[Node("test_main.py", 150)]),
])
show(root)
print(f"files {count_files(root)}, total size {total_size(root)}, height {height(root)}")
Output
project/
  README.md 120
  src/
    main.py 300
    util.py 80
  tests/
    test_main.py 150
files 4, total size 650, height 2
  • Verdict: idiom. Python has no general tree type. A dataclass with a children list is a node.
  • field(default_factory=list) gives each node its own list.
  • Each function calls itself on the children.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

struct Node {
    std::string name;
    int size = 0;
    std::vector<Node> children;
};

void show(const Node& node, int depth) {
    std::string indent(depth * 2, ' ');
    if (node.children.empty()) {
        std::cout << indent << node.name << ' ' << node.size << '\n';
        return;
    }
    std::cout << indent << node.name << "/\n";
    for (const Node& child : node.children) {
        show(child, depth + 1);
    }
}

int count_files(const Node& node) {
    if (node.children.empty()) {
        return 1;
    }
    int count = 0;
    for (const Node& child : node.children) {
        count += count_files(child);
    }
    return count;
}

int total_size(const Node& node) {
    int total = node.size;
    for (const Node& child : node.children) {
        total += total_size(child);
    }
    return total;
}

int height(const Node& node) {
    int best = 0;
    for (const Node& child : node.children) {
        best = std::max(best, 1 + height(child));
    }
    return best;
}

int main() {
    Node root{"project", 0, {
        {"README.md", 120, {}},
        {"src", 0, {{"main.py", 300, {}}, {"util.py", 80, {}}}},
        {"tests", 0, {{"test_main.py", 150, {}}}},
    }};
    show(root, 0);
    std::cout << "files " << count_files(root) << ", total size " << total_size(root)
              << ", height " << height(root) << '\n';
}
Output
project/
  README.md 120
  src/
    main.py 300
    util.py 80
  tests/
    test_main.py 150
files 4, total size 650, height 2
  • Verdict: idiom. A struct can hold a std::vector of its own type, because the vector stores the children on the heap.
  • Aggregate initialization builds the whole tree in one expression.
JavaGitHub
import java.util.List;

public class Main {
    record Node(String name, int size, List<Node> children) {
        static Node file(String name, int size) {
            return new Node(name, size, List.of());
        }

        static Node dir(String name, Node... children) {
            return new Node(name, 0, List.of(children));
        }
    }

    static void show(Node node, int depth) {
        String indent = "  ".repeat(depth);
        if (node.children().isEmpty()) {
            System.out.println(indent + node.name() + " " + node.size());
            return;
        }
        System.out.println(indent + node.name() + "/");
        for (Node child : node.children()) {
            show(child, depth + 1);
        }
    }

    static int countFiles(Node node) {
        if (node.children().isEmpty()) {
            return 1;
        }
        return node.children().stream().mapToInt(Main::countFiles).sum();
    }

    static int totalSize(Node node) {
        return node.size() + node.children().stream().mapToInt(Main::totalSize).sum();
    }

    static int height(Node node) {
        return node.children().stream().mapToInt(child -> 1 + height(child)).max().orElse(0);
    }

    public static void main(String[] args) {
        Node root = Node.dir("project",
                Node.file("README.md", 120),
                Node.dir("src", Node.file("main.py", 300), Node.file("util.py", 80)),
                Node.dir("tests", Node.file("test_main.py", 150)));
        show(root, 0);
        System.out.println("files " + countFiles(root) + ", total size " + totalSize(root)
                + ", height " + height(root));
    }
}
Output
project/
  README.md 120
  src/
    main.py 300
    util.py 80
  tests/
    test_main.py 150
files 4, total size 650, height 2
  • Verdict: idiom. A record with a List of children is a node. List.of makes the lists unmodifiable.
  • The functions use streams to sum and to find the maximum over the children.
#include <stdio.h>

struct node {
    const char *name;
    int size;
    struct node *first_child;
    struct node *next_sibling;
};

static void show(const struct node *n, int depth) {
    printf("%*s", depth * 2, "");
    if (n->first_child == NULL) {
        printf("%s %d\n", n->name, n->size);
        return;
    }
    printf("%s/\n", n->name);
    for (const struct node *c = n->first_child; c != NULL; c = c->next_sibling) {
        show(c, depth + 1);
    }
}

static int count_files(const struct node *n) {
    if (n->first_child == NULL) {
        return 1;
    }
    int count = 0;
    for (const struct node *c = n->first_child; c != NULL; c = c->next_sibling) {
        count += count_files(c);
    }
    return count;
}

static int total_size(const struct node *n) {
    int total = n->size;
    for (const struct node *c = n->first_child; c != NULL; c = c->next_sibling) {
        total += total_size(c);
    }
    return total;
}

static int height(const struct node *n) {
    int best = 0;
    for (const struct node *c = n->first_child; c != NULL; c = c->next_sibling) {
        int h = 1 + height(c);
        if (h > best) {
            best = h;
        }
    }
    return best;
}

int main(void) {
    struct node test_main = {"test_main.py", 150, NULL, NULL};
    struct node util = {"util.py", 80, NULL, NULL};
    struct node main_py = {"main.py", 300, NULL, &util};
    struct node tests = {"tests", 0, &test_main, NULL};
    struct node src = {"src", 0, &main_py, &tests};
    struct node readme = {"README.md", 120, NULL, &src};
    struct node project = {"project", 0, &readme, NULL};

    show(&project, 0);
    printf("files %d, total size %d, height %d\n", count_files(&project), total_size(&project),
           height(&project));
    return 0;
}
Output
project/
  README.md 120
  src/
    main.py 300
    util.py 80
  tests/
    test_main.py 150
files 4, total size 650, height 2
  • Verdict: idiom. Each node has a pointer to its first child and a pointer to its next sibling, so every node has the same fixed size.
  • The nodes live on the stack of main, so the program allocates no memory.
var root = Node.Dir("project",
    Node.File("README.md", 120),
    Node.Dir("src", Node.File("main.py", 300), Node.File("util.py", 80)),
    Node.Dir("tests", Node.File("test_main.py", 150)));

Show(root, 0);
Console.WriteLine("files " + CountFiles(root) + ", total size " + TotalSize(root) + ", height " + Height(root));

static void Show(Node node, int depth)
{
    string indent = new string(' ', depth * 2);
    if (node.Children.Count == 0)
    {
        Console.WriteLine(indent + node.Name + " " + node.Size);
        return;
    }
    Console.WriteLine(indent + node.Name + "/");
    foreach (Node child in node.Children)
    {
        Show(child, depth + 1);
    }
}

static int CountFiles(Node node) =>
    node.Children.Count == 0 ? 1 : node.Children.Sum(child => CountFiles(child));

static int TotalSize(Node node) => node.Size + node.Children.Sum(child => TotalSize(child));

static int Height(Node node) =>
    node.Children.Count == 0 ? 0 : node.Children.Max(child => 1 + Height(child));

record Node(string Name, int Size, List<Node> Children)
{
    public static Node File(string name, int size) => new(name, size, new List<Node>());

    public static Node Dir(string name, params Node[] children) => new(name, 0, new List<Node>(children));
}
Output
project/
  README.md 120
  src/
    main.py 300
    util.py 80
  tests/
    test_main.py 150
files 4, total size 650, height 2
  • Verdict: idiom. A record with a List<Node> of children is a node.
  • LINQ Sum and Max combine the results of the children. Height checks for a leaf first, because a leaf has no children to compare.
JavaScriptGitHub
const file = (name, size) => ({ name, size, children: [] });
const dir = (name, children) => ({ name, size: 0, children });

function show(node, depth = 0) {
  const indent = "  ".repeat(depth);
  if (node.children.length > 0) {
    console.log(`${indent}${node.name}/`);
    for (const child of node.children) show(child, depth + 1);
  } else {
    console.log(`${indent}${node.name} ${node.size}`);
  }
}

const countFiles = (node) =>
  node.children.length === 0 ? 1 : node.children.reduce((sum, child) => sum + countFiles(child), 0);

const totalSize = (node) => node.size + node.children.reduce((sum, child) => sum + totalSize(child), 0);

const height = (node) => Math.max(0, ...node.children.map((child) => 1 + height(child)));

const root = dir("project", [
  file("README.md", 120),
  dir("src", [file("main.py", 300), file("util.py", 80)]),
  dir("tests", [file("test_main.py", 150)]),
]);
show(root);
console.log(`files ${countFiles(root)}, total size ${totalSize(root)}, height ${height(root)}`);
Output
project/
  README.md 120
  src/
    main.py 300
    util.py 80
  tests/
    test_main.py 150
files 4, total size 650, height 2
  • Verdict: idiom. Plain objects with a children array form the tree.
  • Math.max(0, ...) returns 0 for a leaf, because a leaf has no children to spread.
package main

import (
	"fmt"
	"strings"
)

type node struct {
	name     string
	size     int
	children []*node
}

func file(name string, size int) *node {
	return &node{name: name, size: size}
}

func dir(name string, children ...*node) *node {
	return &node{name: name, children: children}
}

func show(n *node, depth int) {
	indent := strings.Repeat("  ", depth)
	if len(n.children) == 0 {
		fmt.Printf("%s%s %d\n", indent, n.name, n.size)
		return
	}
	fmt.Printf("%s%s/\n", indent, n.name)
	for _, child := range n.children {
		show(child, depth+1)
	}
}

func countFiles(n *node) int {
	if len(n.children) == 0 {
		return 1
	}
	count := 0
	for _, child := range n.children {
		count += countFiles(child)
	}
	return count
}

func totalSize(n *node) int {
	total := n.size
	for _, child := range n.children {
		total += totalSize(child)
	}
	return total
}

func height(n *node) int {
	best := 0
	for _, child := range n.children {
		if h := 1 + height(child); h > best {
			best = h
		}
	}
	return best
}

func main() {
	root := dir("project",
		file("README.md", 120),
		dir("src", file("main.py", 300), file("util.py", 80)),
		dir("tests", file("test_main.py", 150)),
	)
	show(root, 0)
	fmt.Printf("files %d, total size %d, height %d\n", countFiles(root), totalSize(root), height(root))
}
Output
project/
  README.md 120
  src/
    main.py 300
    util.py 80
  tests/
    test_main.py 150
files 4, total size 650, height 2
  • Verdict: idiom. A struct with a slice of *node pointers is a node.
  • show prints the directories with a slash, and the files with their size.
RustGitHub
struct Node {
    name: String,
    size: u32,
    children: Vec<Node>,
}

fn file(name: &str, size: u32) -> Node {
    Node {
        name: name.to_string(),
        size,
        children: Vec::new(),
    }
}

fn dir(name: &str, children: Vec<Node>) -> Node {
    Node {
        name: name.to_string(),
        size: 0,
        children,
    }
}

fn show(node: &Node, depth: usize) {
    let indent = "  ".repeat(depth);
    if node.children.is_empty() {
        println!("{indent}{} {}", node.name, node.size);
        return;
    }
    println!("{indent}{}/", node.name);
    for child in &node.children {
        show(child, depth + 1);
    }
}

fn count_files(node: &Node) -> usize {
    if node.children.is_empty() {
        return 1;
    }
    node.children.iter().map(count_files).sum()
}

fn total_size(node: &Node) -> u32 {
    node.size + node.children.iter().map(total_size).sum::<u32>()
}

fn height(node: &Node) -> usize {
    node.children.iter().map(|child| 1 + height(child)).max().unwrap_or(0)
}

fn main() {
    let root = dir(
        "project",
        vec![
            file("README.md", 120),
            dir("src", vec![file("main.py", 300), file("util.py", 80)]),
            dir("tests", vec![file("test_main.py", 150)]),
        ],
    );
    show(&root, 0);
    println!(
        "files {}, total size {}, height {}",
        count_files(&root),
        total_size(&root),
        height(&root)
    );
}
Output
project/
  README.md 120
  src/
    main.py 300
    util.py 80
  tests/
    test_main.py 150
files 4, total size 650, height 2
  • Verdict: idiom. A struct can hold a Vec of its own type, because the vector stores the children on the heap.
  • Each node owns its children. Dropping the root drops the whole tree.
  • Binary tree. Each node has at most two children, left and right. "Binary trees are a commonly used type, which constrain the number of children for each parent to at most two."1
  • Ordered and unordered children. In a file tree, the order of the children often does not matter. In a syntax tree, it does: the two operands of a - b must not swap. Wikipedia: "Typically siblings have an order, with the first one conventionally drawn on the left."1
  • Search trees. A binary search tree, a red-black tree and a B-tree keep keys in order for fast lookup. They are algorithms, and they live on the algorithm site.
  • Forest. "A set of one or more disjoint trees."1
  • Recursive types. A tree type refers to itself: a node holds nodes. See recursive-type.
  • Graph. When a node can have more than one parent, or the links can form a cycle, the structure is a graph. See graph.

Pitfalls

One node under two parents

If a program puts the same node object under two parents, the structure is no longer a tree. A change under one parent shows under the other, and a walk visits the node twice. Wikipedia notes that in file systems, "symbolic links create non-tree graphs, as do multiple hard links to the same file or directory".1

This code runs but gives a wrong answer on purpose.

const logo = { name: "logo.png", size: 50, children: [] };
const site = {
  name: "site",
  size: 0,
  children: [
    { name: "home", size: 0, children: [logo] },
    { name: "about", size: 0, children: [logo] },
  ],
};

logo.name = "logo-v2.png";
console.log(site.children.map((page) => page.children[0].name).join(", "));

const total = (node) => node.size + node.children.reduce((sum, child) => sum + total(child), 0);
console.log("total size:", total(site));
Output
logo-v2.png, logo-v2.png
total size: 100

The file has a size of 50, but the total counts it twice. Copy the node for the second parent, or treat the structure as a graph and keep a set of visited nodes.

A shared default list in Python

In Python, a default argument value is created once. The tutorial warns: "The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list".8 A node class with children=[] gives every node the same list.

This code runs but gives a wrong answer on purpose.

class Node:
    def __init__(self, name, children=[]):
        self.name = name
        self.children = children


root = Node("root")
a = Node("a")
root.children.append(a)
print("children of a:", [child.name for child in a.children])
print("same list:", "yes" if a.children is root.children else "no")
Output
children of a: ['a']
same list: yes

The node a is now its own child. Use None as the default and create the list in the body, or use field(default_factory=list) as in the Idea example.

Deep trees and recursion

A recursive walk uses one stack frame per level. A tree that is very deep, such as a long chain of nodes, can go over the limit. Python's recursion limit is "the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python."9

This code runs but gives a wrong answer on purpose.

class Node:
    def __init__(self, children=None):
        self.children = children or []


def height(node):
    return max((1 + height(child) for child in node.children), default=0)


def height_with_stack(root):
    best = 0
    stack = [(root, 0)]
    while stack:
        node, depth = stack.pop()
        best = max(best, depth)
        stack.extend((child, depth + 1) for child in node.children)
    return best


node = Node()
for _ in range(5000):
    node = Node([node])

try:
    print("recursive height:", height(node))
except RecursionError:
    print("recursive height: RecursionError")
print("height with a stack:", height_with_stack(node))
Output
recursive height: RecursionError
height with a stack: 5000

For trees that can be deep, such as parsed input from users, walk with an explicit stack. See stack-data-structure.

Cost

Operation Children lists With parent pointers
visit every node linear linear
go to a child constant constant
go to the parent linear (search from the root) constant
path from a node to the root linear proportional to the depth
add a leaf under a known node constant (amortized) constant (amortized)

A recursive walk also uses stack space in proportion to the height of the tree.

History

The Path.walk method of Python's pathlib was "Added in version 3.12."5

References

  1. Tree (abstract data type), Wikipedia, the introduction; Terminology; Traversal and search methods; Representations; Applications
  2. Introduction to the DOM, MDN Web Docs, What is the DOM?
  3. ast, Abstract syntax trees, Python documentation, the introduction; ast.walk
  4. Node, MDN Web Docs, Instance properties
  5. pathlib, Object-oriented filesystem paths, Python documentation, Path.walk
  6. TreeMap (Java SE 27 and JDK 27), the class description
  7. Module std::collections, The Rust Standard Library, the module description
  8. More Control Flow Tools, The Python Tutorial, Default Argument Values
  9. sys, System-specific parameters and functions, Python documentation, sys.getrecursionlimit

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/T7XMZM/text.yaml