Trees: one parent each
A tree is a set of nodes connected by parent–child links, starting from a single root. Every node except the root has exactly one parent; a node can have any number of children. Nodes without children are leaves. The depth of a node is its distance from the root; the height of the tree is the greatest depth.
The one-parent rule is what makes something a tree: there's exactly one path from the root to each node, and no loops. Any data with a strict containment or reporting hierarchy fits naturally.
Folders and files on disk, the HTML document (DOM), an org chart, nested comments, a JSON document, the categories of an online shop.
In code: Python · Rust
tree = {"/": {"home": {"ann": {"a.txt": None}, "bo": {}}, "etc": {"hosts": None}}}
class Node:
def __init__(self, name, children=None):
self.name, self.children = name, children or []struct Node {
name: String,
children: Vec<Node>, // each child owned by exactly one parent
}
let root = Node { name: "/".into(), children: vec![
Node { name: "home".into(), children: vec![] },
]};- Rust's ownership model matches trees well: each child is owned by exactly one parent. Pointers back to the parent are where it gets harder (Rc and Weak).
- Nested dicts and JSON are trees; that's why recursive functions handle them so naturally.