Originally published on CodingCush.
A tree is a way of storing data in branches instead of in one long line. Think of a family tree: one item at the top, a few below it, and each of those with its own items underneath. Each box of data is called a node, the lines between boxes are called edges, and the top box is called the root. Trees make finding things fast: one item among thousands, found without checking them all.
The problem: finding one name in a pile of ten thousand
Imagine a teacher with ten thousand students on one plain attendance sheet. A parent phones in: "Is my daughter Anaya on the list?" The only way to answer is to start at the top and read every name until you find hers.
That is the cost of a flat list. An array stores items one after another, and a linked list, explained simply in our earlier guide, stores each item with a pointer to the next one. Searching either one means walking the line from the start, because a list only knows "next".
Can we arrange the same data so each step throws away a big chunk of what is left? Yes, and it looks like a tree.
The fix: let the data branch
Think about finding a file. You open Documents, then Projects, then website, then images, and there it is. You never open every folder on the disk, because each folder narrows the search.
A tree does the same thing with data. As the Programiz guide to the tree data structure puts it, a tree is a nonlinear hierarchical data structure that consists of nodes connected by edges. Nonlinear means the data is not in one straight line. Here are the words you will keep meeting:
Node. One box of data, holding a value and links to the nodes below it. Edge. The link between two nodes. Root. The topmost node, and the only one with no parent.
Parent and child. The node above is the parent, the one below is the child. Every node except the root has exactly one parent, and there are no loops. Children of one parent are siblings.
Leaf. A node with no children, the end of a branch. Height and depth. Depth is the edges from a node to the root. Height is the longest path from a node down to a leaf.
The tree you will meet first: the binary search tree
The most common tree in beginner courses is the binary search tree, or BST. A binary tree is a tree where each node has at most two children. A BST adds one sorting rule at every node: all values in the left subtree are smaller than the node, and all values in the right subtree are larger.
That rule turns searching into higher or lower. Start at the root. Smaller? Go left. Larger? Go right. Match? Found it. Each step throws away half of what is left. The Programiz guide says a BST can search in O(log n) time, and our guide to Big O notation, explained simply, unpacks what that means.
One working example: build a small BST in Python
Enough theory. Here is a complete BST in Python, with insert, search, and an inorder print that shows the values in sorted order. It follows the steps the Programiz BST guide describes, and it was run on this machine, so the output below is real.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(node, key):
# Empty spot: create the new node
if node is None:
return Node(key)
# Smaller goes left, larger goes right
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return node
def search(node, key):
# Empty spot: the value is not here
if node is None:
return None
if key == node.key:
return node
if key < node.key:
return search(node.left, key)
return search(node.right, key)
def inorder(root):
if root is not None:
inorder(root.left)
print(root.key, end=" ")
inorder(root.right)
root = None
for number in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, number)
print("Inorder traversal (sorted order):")
inorder(root)
print()
for target in [40, 90]:
found = search(root, target)
if found is not None:
print(target, "found in the tree")
else:
print(target, "not found in the tree")
Each Node holds one value plus left and right links. Insert walks down comparing as it goes: smaller goes left, larger goes right, and an empty spot gets the new node. Insert and search call themselves to go down a level at a time: that is recursion, and our guide to recursion, explained with examples, covers it in detail.
The inorder print visits the left subtree, then the node, then the right subtree. Smaller values always sit on the left, so the numbers print in sorted order. Here is the real output:
Inorder traversal (sorted order):
20 30 40 50 60 70 80
40 found in the tree
90 not found in the tree
Trace the search for 40. Start at the root, 50. 40 is smaller, so go left to 30. 40 is larger, so go right: three comparisons. The search for 90 walks down the right side, 50, 70, 80, then hits an empty spot.
The Programiz Tree Data Structure page, where this post's definition and tree diagram come from.
Tree vs linked list: a quick comparison
Same nodes, different shape:
| Binary search tree | Linked list | |
|---|---|---|
| Shape | Branches, like folders | One straight line |
| Finding one item | About O(log n) when balanced | O(n), walk from the start |
| Inserting a new item | Walk down to the spot | Fast at the right spot |
| Staying in sorted order | Built in by the sorting rule | Extra work on every insert |
| Memory per item | Two links per node | One link per node |
| Best for | Searching and sorted data | Simple queues of items |
Neither one wins everywhere. A list is simpler for adding and removing at the ends. A tree wins when you search again and again.
Trees also run your day quietly. Your file system is a tree, a web page is a DOM tree, databases index with B-trees, routers use tries, and compilers build syntax trees. The Wikipedia article on the tree data structure lists these classic uses and more.
Common mistakes and troubleshooting
Forgetting the sorting rule. Inserting values without comparing builds a plain binary tree that only looks like a BST, and search then gives wrong answers. Fix: never attach a node without walking down with comparisons first.
Building a lopsided tree. Insert 1, 2, 3, 4, 5 in order and each node goes right, right, right, so the tree becomes a line in disguise. Fix: insert in a mixed order; real systems use self balancing trees like AVL trees.
Forgetting the empty tree. Searching an empty tree, or past a leaf, reaches a None node, and reading node.key there crashes. Fix: check for None first, as the search function above does.
Reading inorder output as the shape. Inorder shows sorted values, not the shape. Two different trees can print the same sorted line. Fix: sketch the tree on paper from the insert order.
Quick answers
Is a tree the same as a binary tree?
No. A tree is the general idea: nodes joined by edges in a branching shape. A binary tree is one kind, where each node has at most two children. A binary search tree adds the sorting rule: smaller on the left, larger on the right.
What is the difference between a tree and a linked list?
A linked list is a line: each node points to the next one, so finding an item means walking from the start. A tree branches, so each step throws away a whole section. Lists are simpler; trees search faster.
When should I use a tree?
Use one when you search often, data keeps arriving, and you want results in sorted order. That covers phone books, file systems, database indexes, and autocomplete. If you only add items at the end and read them in order, a list is enough.
A tiny quiz before you go
Three quick questions to check what stuck. Guess first, then check.
1. In a binary search tree with root 50, where does 20 go, left or right? Left, because 20 is smaller than 50, and smaller values go left.
2. Which node has no parent? The root. Every other node has exactly one parent.
3. You insert 1, 2, 3, 4, 5 in order into an empty BST. What shape do you get? A straight line leaning right, as slow to search as a list. That is why balanced trees matter.
Next step: run the Python example, then change the insert list to your own numbers. Then draw the tree those numbers build, one insert at a time. Once the shape feels natural, try the AVL tree, which stays balanced no matter what order the data arrives in.

Top comments (0)