Tree Representation
in Python
Learn how to represent tree data structures using node objects and adjacency lists: the two foundational approaches every programmer needs.
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.
Key Terminology
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.
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.
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.
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = 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.
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
Example 1: File System Tree
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.
"/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.
def dfs_node(node):
if node is None:
return
print(node.val)
for child in node.children:
dfs_node(child)
def dfs_adj(tree, node):
print(node)
for child in tree[node]:
dfs_adj(tree, child)
When to Use Which Approach
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.
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
parent = {}
for node, kids in tree.items():
for kid in kids:
parent[kid] = node
Common Mistakes
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?
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?