Representing Rooted Trees
The linked list stores a sequence with pointers. The same idea stores a rooted tree: each node is an object with a key and pointers to its relatives. For binary trees the choice of pointers is obvious. For trees in which a node may have any number of children (a file system, an HTML document, a company chart) it is not, and the classic answer, the left-child, right-sibling representation, turns any rooted tree into a binary tree with the same nodes.
The DSA course introduces trees and binary trees and their traversals. This lesson is about the memory layout and what each layout makes cheap.
Binary trees
A node of a binary tree has fields , , and usually . The tree itself is a pointer ; NIL children mark missing subtrees, and the root's parent is NIL. The parent pointer costs one field per node, but it lets an algorithm walk up the tree, which the successor and deletion procedures of binary search trees need.
A traversal visits every node once, so it takes time: each node is entered once from its parent and left once. Recursion uses the call stack; an explicit stack does the same job without recursion, which matters in Python, where deep recursion fails.
class Node:
__slots__ = ("key", "left", "right", "parent")
def __init__(self, key, left=None, right=None):
self.key, self.left, self.right, self.parent = key, left, right, None
for c in (left, right):
if c is not None:
c.parent = self
def preorder_recursive(x, out):
if x is not None:
out.append(x.key)
preorder_recursive(x.left, out)
preorder_recursive(x.right, out)
return out
def preorder_stack(root):
out, stack = [], [root] if root else []
while stack:
x = stack.pop()
out.append(x.key)
if x.right: stack.append(x.right) # pushed first, so visited after the left subtree
if x.left: stack.append(x.left)
return out
def depth(x):
d = 0
while x.parent is not None: # climb with parent pointers
x, d = x.parent, d + 1
return d
leaf = Node("H")
root = Node("A", Node("B", Node("D"), Node("E", leaf)), Node("C", None, Node("F", Node("G"))))
print("recursive preorder:", preorder_recursive(root, []))
print("stack preorder: ", preorder_stack(root))
print("depth of H:", depth(leaf), "| path to root:", end=" ")
x = leaf
while x:
print(x.key, end=" "); x = x.parent
print()
chain = Node(0) # a path of 100,000 nodes
for k in range(1, 100_000):
chain = Node(k, chain)
print("preorder of a 100,000-node path with a stack, first keys:", preorder_stack(chain)[:3])recursive preorder: ['A', 'B', 'D', 'E', 'H', 'C', 'F', 'G']
stack preorder: ['A', 'B', 'D', 'E', 'H', 'C', 'F', 'G']
depth of H: 3 | path to root: H E B A
preorder of a 100,000-node path with a stack, first keys: [99999, 99998, 99997]
The recursive version would raise RecursionError on the 100,000-node path; the explicit stack handles it without trouble.
Trees with unbounded branching
If every node had at most children, fields would do, but most of them would be NIL and may not be known in advance. The left-child, right-sibling representation uses just two pointers per node, whatever the number of children:
- points to the leftmost child of (NIL for a leaf);
- points to the next sibling of to the right (NIL for a rightmost child).
The children of are a singly linked list starting at . Reaching the -th child takes steps, but the total space is , and a full traversal still takes because every pointer is followed once.
A A
/ | \ /
B C D ==> B ---- C ---- D
/ \ | / /
E F G E -- F GOn the right, a downward edge is a first pointer and a horizontal edge is a sibling pointer. Read as a binary tree (first = left, sibling = right), it is an ordinary binary tree: the representation is a bijection between ordered forests and binary trees.
class TNode:
__slots__ = ("name", "first", "sibling", "parent")
def __init__(self, name):
self.name, self.first, self.sibling, self.parent = name, None, None, None
def add_child(p, c): # append c as the last child of p
c.parent = p
if p.first is None:
p.first = c
else:
x = p.first
while x.sibling is not None:
x = x.sibling
x.sibling = c
return c
def children(x):
c = x.first
while c is not None:
yield c
c = c.sibling
def show(x, indent=0):
print(" " * indent + x.name)
for c in children(x):
show(c, indent + 1)
def height(x):
return max((1 + height(c) for c in children(x)), default=0)
root = TNode("/")
home, etc, usr = (add_child(root, TNode(n)) for n in ["home", "etc", "usr"])
ana = add_child(home, TNode("ana"))
for f in ["notes.txt", "photo.png", "todo.md"]:
add_child(ana, TNode(f))
add_child(home, TNode("bo"))
add_child(etc, TNode("hosts"))
add_child(add_child(usr, TNode("bin")), TNode("python3"))
show(root)
print("children of /:", [c.name for c in children(root)], "| height:", height(root))
print("as a binary tree, / has left child", root.first.name, "and no right child:", root.sibling is None)
print("home's binary right child (its next sibling):", home.sibling.name)/
home
ana
notes.txt
photo.png
todo.md
bo
etc
hosts
usr
bin
python3
children of /: ['home', 'etc', 'usr'] | height: 3
as a binary tree, / has left child home and no right child: True
home's binary right child (its next sibling): etc
In C++
The same representation with nodes in a std::vector, indices instead of pointers and for NIL. The tree is the one from the diagram; the program prints each node's children and a preorder traversal, which in this representation is the preorder of the binary tree (visit, then first, then sibling).
#include <cstdio>
#include <string>
#include <vector>
struct Tree {
struct Node { std::string name; int first = -1, sibling = -1, parent = -1; };
std::vector<Node> nodes;
int add(const std::string& name, int parent) {
int id = static_cast<int>(nodes.size());
nodes.push_back({name, -1, -1, parent});
if (parent >= 0) {
int* link = &nodes[parent].first; // walk to the end of the child list
while (*link != -1) link = &nodes[*link].sibling;
*link = id;
}
return id;
}
void preorder(int x, std::string& out) const { // visit, children (first), then siblings
for (; x != -1; x = nodes[x].sibling) {
out += nodes[x].name;
preorder(nodes[x].first, out);
}
}
};
int main() {
Tree t;
int a = t.add("A", -1);
int b = t.add("B", a);
t.add("C", a);
int d = t.add("D", a);
t.add("E", b); t.add("F", b); t.add("G", d);
for (std::size_t x = 0; x < t.nodes.size(); ++x) {
std::printf("%s:", t.nodes[x].name.c_str());
for (int c = t.nodes[x].first; c != -1; c = t.nodes[c].sibling) std::printf(" %s", t.nodes[c].name.c_str());
std::printf("\n");
}
std::string order;
t.preorder(a, order);
std::printf("preorder: %s\n", order.c_str());
}A: B C D
B: E F
C:
D: G
E:
F:
G:
preorder: ABEFCDG
Other layouts
| Layout | Space | Cheap | Expensive |
|---|---|---|---|
| left, right, parent pointers | 3 pointers per node | everything a binary tree needs | nothing in particular |
| left-child, right-sibling | 2 or 3 pointers per node | traversal, adding a first child | the -th child: |
| array of child lists | in total | the -th child: | inserting a child in the middle |
| parent array only | 1 integer per node | walking up, union-find | finding children: scan |
| implicit array (heap layout) | no pointers at all | index arithmetic | only for nearly complete trees |
The parent array may look useless, since it cannot even list a node's children quickly. But some algorithms only ever walk upwards, and then it is the best possible layout: the disjoint-set forests at the end of this course are exactly a parent array. The implicit layout is the one heaps use (Binary Heaps and the Heap Property).
parent = {"B": "A", "C": "A", "D": "A", "E": "B", "F": "B", "G": "D", "A": None}
def depth(v):
d = 0
while parent[v] is not None:
v, d = parent[v], d + 1
return d
def children_of(v): # needs a scan of the whole array
return [u for u, p in parent.items() if p == v]
print({v: depth(v) for v in sorted(parent)})
print("children of A:", children_of("A"), "| children of E:", children_of("E")){'A': 0, 'B': 1, 'C': 1, 'D': 1, 'E': 2, 'F': 2, 'G': 2}
children of A: ['B', 'C', 'D'] | children of E: []
Test yourself
In the left-child, right-sibling representation, how do you reach the third child of node ?
x.first.first.firstx.first.sibling.siblingx.sibling.sibling.siblingx.child[2]
How much space does the left-child, right-sibling representation of an -node tree use?
- , whatever the degrees
- for maximum degree
Which representation lets you find a node's depth but not its children quickly?
- left, right and parent pointers
- left-child, right-sibling
- a parent array
- an array of child lists