A binary tree is a hierarchical structure where each node has at most two children, called left and . It has a single ; nodes with no children are . It is the basis for BSTs, heaps, and expression trees.
A binary tree is a hierarchical structure where each node has at most two children, called left and . It has a single ; nodes with no children are . It is the basis for BSTs, heaps, and expression trees.
right 1 depth 0 (root)
/ \
2 3 depth 1
/ \
4 5 depth 2 (leaves: 4,5,3)
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def inorder(n): # left, node, right -> 4 2 5 1 3
if n:
inorder(n.left); print(n.val); inorder(n.right)
def preorder(n): # node, left, right -> 1 2 4 5 3
if n:
print(n.val); preorder(n.left); preorder(n.right)
def postorder(n): # left, right, node -> 4 5 2 3 1
if n:
postorder(n.left); postorder(n.right); print(n.val)
A level-order (BFS) traversal uses a queue and visits depth by depth.
| Traversal | Order | Common use |
|---|---|---|
| Inorder | L, N, R | sorted output of a BST |
| Preorder | N, L, R | copy/serialize a tree |
| Postorder | L, R, N | delete a tree, evaluate expr |
| Level-order | by depth | BFS, shortest path on tree |
Each traversal visits every node once → O(n) time, O(h) stack space where h is the height.
Binary trees model naturally hierarchical data (file systems, parse trees, decision trees) and underpin efficient search and sorting structures.
Mastering the four traversals is essential — most tree interview problems are a variation of one of them.