Learn computing fundamentals, programming, algorithms, systems, and software engineering.
A tree is a hierarchical structure made of nodes connected by parent-child links. It has a single root at the top, and every other node has exactly one parent, which means a tree never contains a cycle. A binary tree is the most common kind: each node has at most two children, usually called left and right. A Binary Search Tree (BST) adds a rule — for every node, values in its left subtree are smaller and values in its right subtree are larger — which makes lookups fast. Traversing a tree means visiting its nodes in a systematic order. In-order traversal visits the left subtree, then the node itself, then the right subtree; when applied to a BST it visits the values in sorted order. Pre-order visits the node first, and post-order visits the node last. Which one you pick depends on what you need to compute. A graph is a more general structure: a set of nodes (vertices) connected by edges. Unlike a tree, a graph can have cycles and multiple paths between nodes. Graphs are the model for social networks, maps, and dependencies. They are often stored as an adjacency list — a mapping from each node to the nodes it connects to. A heap is a special tree that keeps the smallest (or largest) value at the root, which is why it powers priority queues. Python provides heaps in the heapq module.
| Term | Definition |
|---|---|
| Node | An element that holds a value |
| Root | The top node with no parent |
| Edge | A connection between two nodes |
| Parent / child | The node above / below an edge |
| Leaf | A node with no children |
| Depth / height | Distance from the root / longest path to a leaf |
A Binary Search Tree keeps values ordered so search is fast: for every node, the left subtree holds smaller values and the right subtree holds larger values.
| Traversal | Order | Use case |
|---|---|---|
| In-order | left → node → right | Sorted output in a BST |
| Pre-order | node → left → right | Copying a tree |
| Post-order | left → right → node | Deleting a tree |
| Tree | Graph | |
|---|---|---|
| Root | Exactly one | Any node can be a start |
| Cycles | None | Allowed |
| Parents | One parent per node | Any number of connections |
| Example | File system, DOM | Maps, social networks |
Recursion mirrors the structure of a tree: each call handles one node and delegates the left and right subtrees to new calls.
Insert three values into a BST, then traverse in-order to read them sorted.
1 2 5 8
An adjacency list maps each node to the list of nodes it points to. This is the standard compact representation.
A -> ['B', 'C'] B -> ['D'] C -> ['D'] D -> []
heapq maintains the smallest value at index 0, which is why it backs a priority queue.
1 3 5