Trees

Hierarchical Data Structures

CS205 Data Structures

┌───┐ │ A │ <── root └─┬─┘ ┌────┴────┐ ┌─┴─┐ ┌─┴─┐ │ B │ │ C │ └─┬─┘ └─┬─┘ ┌──┴──┐ │ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ │ D │ │ E │ │ F │ <── leaves └───┘ └───┘ └───┘

Use arrow keys or buttons to navigate

1 / 22

What Is a Tree?

A tree is a hierarchical data structure consisting of nodes connected by edges.

  • Root — the topmost node (no parent)
  • Children — nodes directly below a node
  • Parent — the node directly above
  • Leaves — nodes with no children
  • Edge — connection between parent and child

Analogy: Family Tree

Like a family tree: one ancestor at the top, descendants branching down. Or a file system: root folder containing subfolders and files.

root ──▶ ┌───┐ │ A │ parent of B, C └─┬─┘ ┌────┴────┐ ┌─┴─┐ ┌─┴─┐ │ B │ │ C │ children of A └─┬─┘ └─┬─┘ ┌──┴──┐ │ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ │ D │ │ E │ │ F │ leaves └───┘ └───┘ └───┘ (no children) Edges: A─B, A─C, B─D, B─E, C─F Nodes: 6 Edges: 5 (always: edges = nodes - 1)
2 / 22

Tree Terminology

depth 0 ──▶ ┌───┐ <── root │ A │ └─┬─┘ ┌─────┼─────┐ depth 1 ──▶ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ │ B │ │ C │ │ D │ siblings └─┬─┘ └───┘ └─┬─┘ ┌──┴──┐ ┌──┴──┐ depth 2 ──▶┌┴─┐ ┌─┴┐ ┌─┴┐ ┌─┴┐ │E │ │ F│ │ G│ │ H│ leaves └──┘ └──┘ └──┘ └──┘ height of tree = 2 (max depth of any node)
  • Root — node with no parent (A)
  • Parent of E — B
  • Children of A — B, C, D
  • Siblings — B, C, D (same parent)
  • Ancestor of E — B, A
  • Descendant of B — E, F
  • Leaf / External — no children (C, E, F, G, H)
  • Internal node — has children (A, B, D)
  • Depth of node — edges from root to node
  • Height of tree — max depth
  • Subtree rooted at B — B, E, F
3 / 22

Formal Definition of a Tree

Recursive Definition

A tree T is either:

  • Empty (null / no nodes), OR
  • A root node r with zero or more subtrees T1, T2, ..., Tk

Each subtree is itself a tree! This recursive structure is why many tree algorithms are naturally recursive.

Key Property

A tree with n nodes always has exactly n - 1 edges. There is exactly one path between any two nodes (no cycles!).

Tree T rooted at A: ┌───┐ │ A │ ── root of T └─┬─┘ ┌────┴────┐ ┌─┴─┐ ┌─┴─┐ │ B │ │ C │ └─┬─┘ └─┬─┘ ┌─┴─┐ ┌──┴──┐ │ D │ │ E │ └───┘ └─────┘ T = { A, subtree T₁ = { B, subtree = {D} }, subtree T₂ = { C, subtree = {E} } }

Think Recursively

Every node is the root of its own subtree. "Zoom in" on any node and you see a smaller tree.

4 / 22

Tree ADT (Abstract Data Type)

Accessor Methods

MethodDescription
root()Return the root node
parent(v)Return parent of v
children(v)Return children of v
size()Number of nodes

Query Methods

MethodDescription
isInternal(v)Does v have children?
isExternal(v)Is v a leaf?
isRoot(v)Is v the root?

Computed Properties

depth(v): if isRoot(v): return 0 else: return 1 + depth(parent(v)) height(T): if isExternal(T): return 0 else: h = 0 for each child c of T: h = max(h, height(c)) return 1 + h

Notice

depth() goes up toward root. height() goes down toward leaves. Both are recursive!

5 / 22

Depth and Height

depth=0, height=3 ──▶ ┌───┐ │ A │ └─┬─┘ ┌────┴────┐ depth=1, h=2 ──▶ ┌─┴─┐ ┌─┴─┐ ◀── depth=1, h=0 │ B │ │ C │ (leaf) └─┬─┘ └───┘ ┌────┴────┐ depth=2 ──▶┌─┴─┐ ┌─┴─┐ ◀── depth=2, h=0 │ D │ │ E │ └─┬─┘ └───┘ │ depth=3 ──▶┌─┴─┐ ◀── deepest leaf │ F │ h=0 └───┘

Depth of a Node

Depth(v) = number of edges from root to v.
Root has depth 0. Goes top-down.

Height of a Node

Height(v) = number of edges on the longest path from v down to a leaf.
Leaves have height 0. Goes bottom-up.

Height of Tree

Height(T) = height of the root = max depth of any leaf.

Here: height(A) = 3, because the longest path is A → B → D → F.

6 / 22

Binary Trees

A binary tree is a tree where each node has at most 2 children: a left child and a right child.

┌───┐ │ 8 │ └─┬─┘ ┌────┴────┐ ┌─┴─┐ ┌─┴─┐ │ 3 │ │ 10│ └─┬─┘ └─┬─┘ ┌──┴──┐ └──┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ │ 1 │ │ 6 │ │ 14│ └───┘ └───┘ └───┘ left right right child child child only

Properties of Binary Trees

PropertyValue
Max nodes at depth d2d
Max leaves (height h)2h
Max total nodes2h+1 - 1
Min height (n nodes)⌊log2 n⌋

Why Binary?

Binary trees are the most common tree structure in CS. They enable efficient searching, sorting, and expression evaluation.

Left vs Right Matters!

In a binary tree, a node with only one child — it matters whether it's the left or right child. They are structurally different.

7 / 22

Full vs Complete vs Perfect Binary Trees

FULL Binary Tree COMPLETE Binary Tree PERFECT Binary Tree Every node has All levels full except All internal nodes have 0 or 2 children last; last filled L→R 2 children; all leaves (no single-child nodes) at the same depth ┌───┐ ┌───┐ ┌───┐ │ A │ │ A │ │ A │ └─┬─┘ └─┬─┘ └─┬─┘ ┌───┴───┐ ┌───┴───┐ ┌───┴───┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ │ B │ │ C │ │ B │ │ C │ │ B │ │ C │ └─┬─┘ └───┘ └─┬─┘ └─┬─┘ └─┬─┘ └─┬─┘ ┌──┴──┐ (leaf) ┌──┴──┐ │ ┌──┴──┐ ┌──┴──┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐┌─┴─┐ ┌─┴─┐┌─┴─┐┌─┴┐┌─┴┐ │ D │ │ E │ │ D │ │ E ││ F │ │ D ││ E ││ F││ G│ └───┘ └───┘ └───┘ └───┘└───┘ └───┘└───┘└──┘└──┘
TypeRuleRelationship
FullEvery node: 0 or 2 childrenNot necessarily complete
CompleteAll levels full; last level left-filledUsed in heaps!
PerfectAll leaves at same depth, all internals have 2 childrenBoth full AND complete

Perfect binary tree has exactly 2h+1 - 1 nodes (all slots filled)

8 / 22

Binary Tree Traversals Overview

Traversal = visiting every node exactly once in a specific order.

TraversalOrderMnemonic
PreorderNode, Left, RightNLR
InorderLeft, Node, RightLNR
PostorderLeft, Right, NodeLRN
Level-orderTop to bottom, L to RBFS

Why Different Orders?

  • Preorder — copy/serialize a tree
  • Inorder — sorted output from BST
  • Postorder — delete tree, evaluate expressions
  • Level-order — find shortest path, BFS

Reference tree for next slides:

┌───┐ │ A │ └─┬─┘ ┌────┴────┐ ┌─┴─┐ ┌─┴─┐ │ B │ │ C │ └─┬─┘ └─┬─┘ ┌──┴──┐ └──┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ │ D │ │ E │ │ F │ └───┘ └───┘ └───┘

The "N" Position

The mnemonic tells you when you visit the node: before children (pre), between children (in), or after children (post).

9 / 22

Preorder Traversal (NLR)

Visit node FIRST, then recurse left, then recurse right.

Visit order: A B D E C F ┌───┐ ① │ A │ └─┬─┘ ┌────┴────┐ ┌─┴─┐ ┌─┴─┐ ② │ B │ ⑤ │ C │ └─┬─┘ └─┬─┘ ┌──┴──┐ └──┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ③ │ D │ │ E │ ④ ⑥ │ F │ └───┘ └───┘ └───┘ Process: Visit A → go left Visit B → go left Visit D → (leaf, backtrack) Visit E → (leaf, backtrack) Visit C → go left (null) → go right Visit F → (leaf, done)
preorder(node): if node == null: return visit(node) // process FIRST preorder(node.left) preorder(node.right)

Use Cases

  • Create a copy of the tree
  • Serialize a tree to a string
  • Print a prefix expression
  • Generate table of contents from document tree

Analogy: Reading a Book

Read chapter title first (node), then read sections in order (left to right children).

10 / 22

Inorder Traversal (LNR)

Recurse left, visit node IN THE MIDDLE, then recurse right.

Visit order: D B E A C F ┌───┐ ④ │ A │ └─┬─┘ ┌────┴────┐ ┌─┴─┐ ┌─┴─┐ ② │ B │ ⑤ │ C │ └─┬─┘ └─┬─┘ ┌──┴──┐ └──┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ① │ D │ │ E │ ③ ⑥ │ F │ └───┘ └───┘ └───┘ Process: Go left from A → left from B Visit D (leaf) → back to B Visit B → go right Visit E (leaf) → back to A Visit A → go right Visit C → go right Visit F
inorder(node): if node == null: return inorder(node.left) visit(node) // process MIDDLE inorder(node.right)

Sorted Output from BST!

Inorder traversal of a Binary Search Tree visits nodes in ascending sorted order. This is the most important traversal for BSTs.

BST inorder example: ┌──┐ │8 │ └┬─┘ ┌──┴──┐ ┌─┴┐ ┌─┴┐ │3 │ │10│ └┬─┘ └──┘ ┌─┴─┐ ┌┴┐ ┌┴┐ │1│ │6│ └─┘ └─┘ Output: 1, 3, 6, 8, 10 ✓ sorted!
11 / 22

Postorder Traversal (LRN)

Recurse left, recurse right, visit node LAST.

Visit order: D E B F C A ┌───┐ ⑥ │ A │ └─┬─┘ ┌────┴────┐ ┌─┴─┐ ┌─┴─┐ ③ │ B │ ⑤ │ C │ └─┬─┘ └─┬─┘ ┌──┴──┐ └──┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ① │ D │ │ E │ ② ④ │ F │ └───┘ └───┘ └───┘ Process: Go left from A → left from B Visit D (leaf) → right of B Visit E (leaf) → back to B Visit B → right of A → right of C Visit F (leaf) → back to C Visit C → back to A Visit A (last!)
postorder(node): if node == null: return postorder(node.left) postorder(node.right) visit(node) // process LAST

Use Cases

  • Delete/free a tree (children before parent)
  • Evaluate expression trees (compute children before combining)
  • Calculate directory sizes (files before folder totals)

Why "Post"?

The root is always visited last. You must finish all descendants before processing a node. Think: "clean up children before yourself."

12 / 22

Level-Order Traversal (BFS)

Visit nodes level by level, left to right. Uses a queue (not recursion).

Visit order: A B C D E F Level 0: ┌───┐ ① │ A │ └─┬─┘ ┌─────┴─────┐ Level 1: ┌─┴─┐ ┌─┴─┐ ② │ B │ ③ │ C │ └─┬─┘ └─┬─┘ ┌──┴──┐ └──┐ Level 2:┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ④ │ D │ │ E │⑤⑥ │ F │ └───┘ └───┘ └───┘ → Read like a book: left to right, top to bottom.
levelOrder(root): queue Q Q.enqueue(root) while Q is not empty: node = Q.dequeue() visit(node) if node.left != null: Q.enqueue(node.left) if node.right != null: Q.enqueue(node.right)
Queue trace: Step 1: Q=[A] → visit A, enqueue B,C Step 2: Q=[B,C] → visit B, enqueue D,E Step 3: Q=[C,D,E] → visit C, enqueue F Step 4: Q=[D,E,F] → visit D Step 5: Q=[E,F] → visit E Step 6: Q=[F] → visit F Step 7: Q=[] → done!

Not Recursive!

This is the only standard traversal that uses a queue instead of recursion (or a stack).

13 / 22

Binary Search Tree (BST)

BST Property

For every node v in the tree:

  • All keys in v's left subtree < v's key
  • All keys in v's right subtree > v's key

This must hold for every node, not just the root!

┌────┐ │ 15 │ └──┬─┘ ┌─────┴─────┐ ┌─┴─┐ ┌─┴──┐ │ 8 │ │ 22 │ └─┬─┘ └──┬─┘ ┌───┴───┐ ┌───┴───┐ ┌─┴─┐ ┌─┴──┐ ┌┴──┐ ┌─┴──┐ │ 4 │ │ 12 │ │18 │ │ 25 │ └───┘ └────┘ └───┘ └────┘ All left of 15: {4,8,12} < 15 ✓ All right of 15: {18,22,25} > 15 ✓ All left of 8: {4} < 8 ✓ All right of 8: {12} > 8 ✓

Analogy: Phone Book

Like binary search on a sorted array, but stored as a tree. At each node you decide: go left (smaller) or go right (larger).

Why BST?

OperationBST (balanced)ArrayLinked List
SearchO(log n)O(log n)*O(n)
InsertO(log n)O(n)O(1)**
DeleteO(log n)O(n)O(n)

* sorted array with binary search
** insert at head, but finding position is O(n)

BST gives O(log n) for ALL three operations when balanced!

14 / 22

BST Search

Compare target with current node. Go left if smaller, right if larger.

Search for 12:

Step 1: Compare 12 with 15 12 < 15 → go LEFT ┌────┐ │ 15 │ ◀── start here └──┬─┘ ┌─────┴─────┐ ┌─┴─┐ ┌─┴──┐ ──▶ │ 8 │ │ 22 │ └─┬─┘ └──┬─┘ ┌───┴───┐ ┌───┴───┐ ┌─┴─┐ ┌─┴──┐ ┌┴──┐ ┌─┴──┐ │ 4 │ │ 12 │ │18 │ │ 25 │ └───┘ └────┘ └───┘ └────┘ Step 2: Compare 12 with 8 12 > 8 → go RIGHT Step 3: Compare 12 with 12 12 == 12 → FOUND! ✓ Path: 15 → 8 → 12 (3 comparisons)
search(node, key): if node == null: return null // not found if key == node.key: return node // found! else if key < node.key: return search(node.left, key) else: return search(node.right, key)

Each comparison eliminates half the tree

Like binary search on an array! Each step goes down one level, so the number of comparisons equals the depth of the target node.

Search for 9 (not in tree):

15 → 8 → 12 → left of 12 is NULL → return null (not found) We always end at a null child when the key doesn't exist.
15 / 22

BST Insert

Search for the key. When you reach null, that is where the new node goes.

Insert 10 into BST:

BEFORE: ┌────┐ │ 15 │ └──┬─┘ ┌─────┴─────┐ ┌─┴─┐ ┌─┴──┐ │ 8 │ │ 22 │ └─┬─┘ └────┘ ┌───┴───┐ ┌─┴─┐ ┌─┴──┐ │ 4 │ │ 12 │ └───┘ └────┘ Search path for 10: 15 → (10<15) left → 8 → (10>8) right → 12 → (10<12) left → NULL! AFTER: insert 10 as left child of 12 ┌────┐ │ 15 │ └──┬─┘ ┌─────┴─────┐ ┌─┴─┐ ┌─┴──┐ │ 8 │ │ 22 │ └─┬─┘ └────┘ ┌───┴───┐ ┌─┴─┐ ┌─┴──┐ │ 4 │ │ 12 │ └───┘ └──┬─┘ ┌─┴──┐ │ 10 │ ◀── NEW! └────┘
insert(node, key): if node == null: return new Node(key) // create leaf if key < node.key: node.left = insert(node.left, key) else if key > node.key: node.right = insert(node.right, key) // if key == node.key: duplicate, skip return node

New nodes are always leaves!

Insert never modifies existing nodes. It simply creates a new leaf at the correct position.

Insertion Order Matters

Inserting 1, 2, 3, 4, 5 in order creates a skewed tree (linked list!). Different insertion orders create different tree shapes.

Analogy

Like filing a paper: walk through the file cabinet making left/right decisions until you find the empty slot.

16 / 22

BST Delete: Three Cases

CASE 1: Leaf Node CASE 2: One Child CASE 3: Two Children (Just remove it) (Replace with child) (Find inorder successor) Delete 4: Delete 22: Delete 8: BEFORE: AFTER: BEFORE: AFTER: BEFORE: AFTER: ┌──┐ ┌──┐ ┌──┐ ┌──┐ ┌──┐ ┌──┐ │15│ │15│ │15│ │15│ │15│ │15│ └┬─┘ └┬─┘ └┬─┘ └┬─┘ └┬─┘ └┬─┘ ┌─┴──┐ ┌─┴──┐ ┌─┴──┐ ┌─┴──┐ ┌──┴──┐ ┌──┴──┐ ┌┴┐ ┌─┴┐ ┌┴┐ ┌─┴┐ ┌┴┐ ┌─┴─┐ ┌┴┐ ┌─┴┐ ┌┴─┐ ┌─┴─┐ ┌┴──┐┌─┴─┐ │8│ │22│ │8│ │22│ │8│ │ 22 │ │8│ │25│ │ 8│ │ 22│ │ 10││ 22│ └┬┘ └──┘ └┬┘ └──┘ └─┘ └──┬─┘ └─┘ └──┘ └┬─┘ └───┘ └┬──┘└───┘ ┌─┴─┐ ┌┴┐ ┌─┴─┐ ┌──┴──┐ ┌─┴─┐ ┌┴┐┌─┴┐ ┌┴─┐ ┌─┴─┐ ┌─┴┐ ┌─┴─┐ ┌┴┐┌─┴─┐ │4││12│ │12│ │ 25│ │ 4│ │ 12│ │4││ 12│ └─┘└──┘ └──┘ └───┘ └──┘ └─┬─┘ └─┘ └───┘ ↑ ↑ ┌─┴┐ simply child 25 │10│ removed moves up └──┘ ↑ successor

The Difficulty Increases with Each Case

Case 1 (leaf): trivial. Case 2 (one child): just bypass. Case 3 (two children): most complex — next slide!

17 / 22

BST Delete: Two Children Case (Detail)

Delete 8 from the BST. Node 8 has two children, so we cannot simply remove it.

Step 1: Find the INORDER SUCCESSOR (smallest value in right subtree) ┌────┐ │ 15 │ └──┬─┘ ┌─────┴─────┐ ┌─┴─┐ ┌─┴──┐ │ 8 │ ◀─ delete │ 22 │ └─┬─┘ this └────┘ ┌───┴───┐ ┌─┴─┐ ┌─┴──┐ │ 4 │ │ 12 │ └───┘ └──┬─┘ ┌─┴──┐ │ 10 │ ◀─ inorder successor! └────┘ (leftmost in right subtree) Inorder successor of 8: Go right to 12, then keep going left. 12 has no left child → but 10 is left of 12 10 has no left child → 10 is the successor!
Step 2: COPY successor's value into the node being deleted ┌────┐ │ 15 │ └──┬─┘ ┌─────┴─────┐ ┌─┴──┐ ┌─┴──┐ │ 10 │ ◀─ was 8 │ 22 │ └──┬─┘ now 10 └────┘ ┌────┴───┐ ┌─┴─┐ ┌──┴─┐ │ 4 │ │ 12 │ └───┘ └──┬─┘ ┌─┴──┐ │ 10 │ ◀─ duplicate! delete this └────┘ Step 3: DELETE the successor (10) from its original position. Successor is a leaf → Case 1 (easy!) ┌────┐ │ 15 │ └──┬─┘ ┌─────┴─────┐ ┌─┴──┐ ┌─┴──┐ │ 10 │ │ 22 │ └──┬─┘ └────┘ ┌────┴───┐ ┌─┴─┐ ┌──┴─┐ │ 4 │ │ 12 │ ✓ BST property intact! └───┘ └────┘

Why Inorder Successor?

The inorder successor is the smallest value larger than the deleted node. It always has at most one child (right only), so deleting it is Case 1 or Case 2. You could also use the inorder predecessor (largest in left subtree).

18 / 22

BST Performance

Balanced BST: O(log n)

Insert order: 8, 4, 12, 2, 6, 10, 14 ┌───┐ │ 8 │ height = 2 └─┬─┘ ┌────┴────┐ ┌─┴─┐ ┌──┴─┐ │ 4 │ │ 12 │ └─┬─┘ └──┬─┘ ┌──┴──┐ ┌──┴──┐ ┌─┴─┐┌─┴┐ ┌┴──┐┌─┴┐ │ 2 ││ 6│ │ 10││14│ └───┘└──┘ └───┘└──┘ n = 7 nodes height = 2 ≈ log₂(7) Search/Insert/Delete: O(log n)

Best Case

Height ~ log2(n). Each operation touches at most h + 1 nodes.

Skewed BST: O(n)

Insert order: 2, 4, 6, 8, 10, 12, 14 ┌───┐ │ 2 │ height = 6 └─┬─┘ └──┐ ┌─┴─┐ │ 4 │ └─┬─┘ └──┐ ┌─┴─┐ │ 6 │ └─┬─┘ └──┐ This is just a ┌─┴─┐ linked list! │ 8 │ └─┬─┘ └──┐ ┌─┴──┐ │ 10 │ └──┬─┘ └──┐ ┌─┴──┐ │ 12 │ └──┬─┘ └──┐ ┌─┴──┐ │ 14 │ └────┘

Worst Case

Sorted input creates a degenerate tree (linked list). Height = n - 1. All operations become O(n)!

19 / 22

Balanced BSTs (Preview)

How do we guarantee O(log n) performance? Self-balancing trees!

AVL Trees

Rule: For every node, the heights of left and right subtrees differ by at most 1. Balance Factor = height(left) - height(right) Must be in {-1, 0, +1} ┌───┐ │ 8 │ BF = 0 └─┬─┘ ┌────┴────┐ ┌─┴─┐ ┌─┴──┐ │ 4 │ │ 12 │ BF = 0 └─┬─┘ └──┬─┘ │ ┌──┴──┐ ┌─┴─┐ ┌─┴──┐┌─┴┐ │ 2 │ │ 10 ││14│ └───┘ └────┘└──┘ When unbalanced → ROTATE to fix!

Red-Black Trees

Rules: 1. Every node is red or black 2. Root is black 3. Red node's children must be black 4. All paths from node to null have same number of black nodes ┌────┐ │ 8B │ (B = black) └──┬─┘ ┌─────┴─────┐ ┌─┴──┐ ┌──┴──┐ │ 4R │ │ 12R │ (R = red) └──┬─┘ └──┬──┘ ┌──┴──┐ ┌──┴──┐ ┌┴──┐┌─┴┐ ┌┴──┐┌─┴┐ │2B ││6B│ │10B││14B│ └───┘└──┘ └───┘└──┘

Both Guarantee O(log n)

AVL trees are more strictly balanced (faster lookup). Red-Black trees do fewer rotations (faster insert/delete). Java's TreeMap uses Red-Black.

Coming Attraction

These will be covered in detail in a future lecture. For now, know they exist and why they're needed: to prevent the O(n) worst case.

20 / 22

Application: Expression Trees

Arithmetic expressions can be represented as binary trees. Operators are internal nodes; operands are leaves.

Expression: (3 + 4) * 2

┌───┐ │ * │ ◀── root = final op └─┬─┘ ┌────┴────┐ ┌─┴─┐ ┌─┴─┐ │ + │ │ 2 │ ◀── leaf (operand) └─┬─┘ └───┘ ┌──┴──┐ ┌─┴─┐ ┌─┴─┐ │ 3 │ │ 4 │ ◀── leaves (operands) └───┘ └───┘

Evaluate with Postorder!

Process children (operands) before parent (operator). Naturally computes the result bottom-up.

Postorder Evaluation Trace:

Step 1: Visit 3 → push 3 Step 2: Visit 4 → push 4 Step 3: Visit + → pop 4,3 → 3+4=7 → push 7 Step 4: Visit 2 → push 2 Step 5: Visit * → pop 2,7 → 7*2=14 → push 14 Result: 14 ✓

Three Traversals = Three Notations:

TraversalOutputNotation
Preorder* + 3 4 2Prefix (Polish)
Inorder3 + 4 * 2Infix (needs parens!)
Postorder3 4 + 2 *Postfix (RPN)

Infix Needs Parentheses

3 + 4 * 2 is ambiguous without parentheses. Prefix and postfix are unambiguous — no parens needed.

21 / 22

Summary & Cheat Sheet

Tree Fundamentals

Tree: hierarchical, n nodes, n-1 edges Binary Tree: at most 2 children per node BST: left < node < right (all subtrees!) Full: every node has 0 or 2 children Complete: all levels filled, last L→R Perfect: all leaves same depth (full slots)

Traversals

NameOrderUse For
PreorderNLRCopy/serialize
InorderLNRSorted output (BST)
PostorderLRNDelete / eval expr
Level-orderBFSLevel-by-level

BST Operations

Search: compare, go left/right → O(h) Insert: search + add leaf → O(h) Delete: Case 1 (leaf): remove Case 2 (one child): bypass Case 3 (two children): → find inorder successor → copy value, delete successor

Complexity

BST TypeHeightOps
BalancedO(log n)O(log n)
SkewedO(n)O(n)

Key Takeaway

Trees let us organize data hierarchically. BSTs give us O(log n) search, insert, and delete — but only when balanced. Self-balancing trees (AVL, Red-Black) guarantee this.

22 / 22