TExcelTAD

Trees Intro

Arrays, linked lists, stacks and queues are linear: every item has at most one successor. A tree is hierarchical: every item can have several children. File systems, HTML documents, company org charts, family trees and the moves of a chess game are all trees.

text
                 /             <- root
          ┌──────┼───────┐
        home    etc     usr     <- children of the root
        ┌─┴─┐    │       │
      ana   ben hosts   bin     <- leaves (no children)

Vocabulary

Term Meaning (in the picture)
Node one item in the tree (home, hosts, …)
Edge the link between a parent and a child
Root the single node with no parent (/)
Parent / child home is the parent of ana; ana is a child of home
Siblings nodes with the same parent (home, etc, usr)
Leaf a node with no children (ana, ben, hosts, bin)
Subtree a node together with all its descendants
Depth of a node number of edges from the root (home: 1, ana: 2)
Height of a tree the largest depth of any node (here 2)

A tree with n nodes always has exactly n - 1 edges, and there is exactly one path between any two nodes. (A structure where you can go in a circle is a graph with a cycle, not a tree.)

A general tree in Python

In a general tree a node may have any number of children, so each node keeps a list:

python · try it yourself
class TreeNode:
    def __init__(self, name, children=None):
        self.name = name
        self.children = children or []

root = TreeNode("/", [
    TreeNode("home", [TreeNode("ana"), TreeNode("ben")]),
    TreeNode("etc", [TreeNode("hosts")]),
    TreeNode("usr", [TreeNode("bin")]),
])

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

show(root)
/
    home
        ana
        ben
    etc
        hosts
    usr
        bin

Recursion fits trees naturally

Every subtree is itself a tree, so most tree algorithms are recursive: solve the problem for each child's subtree, then combine the answers. Counting nodes, finding leaves and measuring height all follow this pattern:

python · try it yourself
class TreeNode:
    def __init__(self, name, children=None):
        self.name = name
        self.children = children or []

root = TreeNode("/", [
    TreeNode("home", [TreeNode("ana"), TreeNode("ben")]),
    TreeNode("etc", [TreeNode("hosts")]),
    TreeNode("usr", [TreeNode("bin")]),
])

def count(node):
    return 1 + sum(count(c) for c in node.children)

def leaves(node):
    if not node.children:
        return [node.name]
    return [leaf for c in node.children for leaf in leaves(c)]

def height(node):
    if not node.children:
        return 0
    return 1 + max(height(c) for c in node.children)

print("nodes:", count(root), " edges:", count(root) - 1)
print("leaves:", leaves(root))
print("height:", height(root))
nodes: 8  edges: 7
leaves: ['ana', 'ben', 'hosts', 'bin']
height: 2

Paths from the root

Because every node has exactly one parent, there is exactly one path from the root to each node, like a file path:

python · try it yourself
class TreeNode:
    def __init__(self, name, children=None):
        self.name = name
        self.children = children or []

root = TreeNode("", [
    TreeNode("home", [TreeNode("ana", [TreeNode("notes.txt")]), TreeNode("ben")]),
    TreeNode("etc", [TreeNode("hosts")]),
])

def find_path(node, target, path=()):
    path = path + (node.name,)
    if node.name == target:
        return "/".join(path)
    for child in node.children:
        found = find_path(child, target, path)
        if found:
            return found
    return None

print(find_path(root, "notes.txt"))
print(find_path(root, "hosts"))
print(find_path(root, "passwd"))
/home/ana/notes.txt
/etc/hosts
None

Kinds of trees in this course

Tree Rule Used for
Binary tree at most 2 children (left, right) the basis of the next ones
Binary search tree left subtree < node < right subtree sorted data with fast search
AVL tree a BST that keeps itself balanced guaranteed O(log n) operations
Heap parent ≤ children (min-heap) priority queues, heap sort
Trie each edge is a character autocomplete, spell checkers

Why trees? A balanced tree with n nodes has height about log₂ n, so walking from the root to any node takes only about log₂ n steps. A balanced binary tree with a million nodes is only about 20 levels deep.

Test yourself

What is a leaf node?

  1. The root
  2. A node with no children
  3. A node with exactly one child
  4. Any node at depth 1

A tree has 12 nodes. How many edges does it have?

  1. 11
  2. 12
  3. 13
  4. 24

What is the height of a tree that consists of only a root?

  1. 0
  2. 1
  3. 2
  4. Undefined