01 / 20

Tree Representation
in Python

Learn how to represent tree data structures using node objects and adjacency lists: the two foundational approaches every programmer needs.

Python Data Structures

What Is a Tree?

A tree is a hierarchical data structure made of nodes connected by edges. Unlike a list, which is linear, a tree branches out: one node can point to many children.

A B C D E F G Root: A | Internal: B, C | Leaves: D, E, F, G

Key Terminology

Root
The topmost node with no parent. The entry point to the entire tree.
Child / Parent
A node directly below another is its child. The node above is its parent.
Leaf
A node with zero children. It sits at the bottom of a branch.
Depth
Number of edges from the root down to a given node.
Height
Number of edges on the longest path from a node down to a leaf.
Subtree
Any node plus all of its descendants form a subtree of the original tree.

Why Represent Trees?

Trees appear everywhere in computing. File systems, HTML DOM, decision trees, and database indexes are all trees. To work with them in code, we need a concrete way to store the nodes and edges.

1
Organize hierarchical data: folders inside folders, categories inside categories.
2
Fast search and insertion: binary search trees operate in \( O(\log n) \) time.
3
Model decisions: each branch in a decision tree represents a choice or outcome.

Representation 1: Node Objects

Each node is a Python object that stores a value and references to its children. This mirrors the tree's structure directly in memory.

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

# Build the tree from Slide 1
d = TreeNode("D")
e = TreeNode("E")
f = TreeNode("F")
g = TreeNode("G")
b = TreeNode("B", [d, e])
c = TreeNode("C", [f, g])
root = TreeNode("A", [b, c])

Binary Tree Node Variant

When every node has at most two children, we use named fields left and right instead of a generic list.

class BinaryNode:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
10 5 15 3 7 .left .right

Representation 2: Adjacency List

Instead of node objects, store the tree as a dictionary. Each key is a node, and its value is the list of its children.

# Adjacency list for the same tree
tree = {
    "A": ["B", "C"],
    "B": ["D", "E"],
    "C": ["F", "G"],
    "D": [],
    "E": [],
    "F": [],
    "G": [],
}

Node Objects vs. Adjacency List

Node Objects Adjacency List
Structure Class instances linked by references Dictionary mapping node → children
Data per node Embed attributes on each object Separate dict or tuple values
Traversal Follow .children / .left Look up tree[node]
Serialization Needs custom logic JSON-ready as-is
Best for OOP designs, rich node data Competitive programming, graphs

How to Build a Tree in Python

1
Choose a representation. Node objects for OOP tasks; adjacency list for quick prototyping.
2
Define the node. For objects: write a class with val and children. For adj-list: create an empty dict.
3
Create leaves first, then parents. Build bottom-up so children exist before you reference them.
4
Link children to parents. Pass children to the constructor (objects) or append to the list (adj-list).
5
Keep a reference to the root. All traversals start from the root node or root key.

Example 1: File System Tree

/root docs src readme notes main utils A file system is a tree: folders are internal nodes, files are leaves
# Node-object approach
readme = TreeNode("readme")
notes  = TreeNode("notes")
main   = TreeNode("main")
utils  = TreeNode("utils")
docs   = TreeNode("docs", [readme, notes])
src    = TreeNode("src", [main, utils])
root   = TreeNode("/root", [docs, src])

Example 2: Adjacency List Version

The exact same file-system tree stored as a dictionary. No classes needed.

tree = {
    "/root": ["docs", "src"],
    "docs":  ["readme", "notes"],
    "src":   ["main", "utils"],
    "readme": [],
    "notes":  [],
    "main":   [],
    "utils":  [],
}

Example 3: Traversing Both Representations

A depth-first traversal works similarly for both. We print each node, then recurse into its children.

# 1) Node-object traversal
def dfs_node(node):
    if node is None:
        return
    print(node.val)
    for child in node.children:
        dfs_node(child)
# 2) Adjacency-list traversal
def dfs_adj(tree, node):
    print(node)
    for child in tree[node]:
        dfs_adj(tree, child)

When to Use Which Approach

Node Objects
Use when each node carries rich data (color, weight, state). Great for object-oriented designs, GUIs, and game trees.
Adjacency List
Use for algorithm contests, graph problems, or when you need to serialize to JSON. Minimal boilerplate.

Extension: Parent Pointers

Sometimes you need to walk up the tree. Add a parent attribute to node objects, or build a reverse mapping in the adjacency list.

# Node object with parent pointer
class TreeNode:
    def __init__(self, val, children=None):
        self.val = val
        self.children = children or []
        self.parent = None
        for c in self.children:
            c.parent = self
# Adjacency list: build parent dict
parent = {}
for node, kids in tree.items():
    for kid in kids:
        parent[kid] = node

Common Mistakes

✕ Mutable Default Argument
Using children=[] in the constructor shares one list across all instances. Always use None and assign inside.
✕ Forgetting Leaves
In adjacency lists, omitting leaf keys means tree[leaf] raises a KeyError. Always include every node, even with an empty list.
✕ Confusing Trees with Graphs
Trees have no cycles. If you accidentally create a cycle (child points back to ancestor), traversals will loop forever.

Summary at a Glance

Concept Node Objects Adjacency List
Python construct class TreeNode dict { node: [children] }
Access children node.children tree[node]
Binary variant node.left, node.right tree[node][0], tree[node][1]
Parent access Add .parent attribute Build reverse dict
Memory model Heap objects with pointers Hash table (dict)
Serialization Custom __repr__ or pickle json.dumps(tree)

Question 1 of 5

In a Python TreeNode class, why should you write children=None instead of children=[] as the default parameter?

Question 2 of 5

Given this adjacency list, how many leaf nodes does the tree have?

tree = {"X": ["Y", "Z"], "Y": ["W"], "Z": [], "W": []}

Question 3 of 5

Which statement is true about a binary tree node compared to a general tree node?

Question 4 of 5

What is the time complexity of looking up a node's children in a Python adjacency list (dictionary)?

Question 5 of 5

Which advantage does the node-object representation have over the adjacency list?