A tree is a non-linear structure for hierarchical data: a file system, the DOM of an HTML document, an org chart, an expression tree. A tree generalizes a linked list: a node has several children instead of one next. There are no cycles, and every node (except the root) has exactly one parent.

Tree terms: root, leaf, level, height
Tree terms: root, leaf, level, height

Terms

TermMeaning
Rootthe only node without a parent
Leafa node without children
Parent / child / siblingdirectly above / below / other children of the same parent
Ancestor / descendantnodes above / below along the path
Depththe number of edges from the root to the node (the root has 0)
Heightthe number of edges from the node to the deepest leaf (a leaf has 0)
Levelthe nodes of the same depth
Subtreea node and all its descendants
Degreethe number of children of a node

The height of a tree is the height of its root. A tree with n nodes has n - 1 edges.

The node class

python
class TreeNode:
    def __init__(self, value, children=None):
        self.value = value
        self.children = children or []

def sample():
    return TreeNode("A", [
        TreeNode("B", [TreeNode("E"), TreeNode("F")]),
        TreeNode("C"),
        TreeNode("D", [TreeNode("G")]),
    ])

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