Lesson 12 +35 XP

Trees, Binary Trees & Tree Traversals

Trees, Binary Trees & Tree Traversals

A Tree is an acyclic, connected, non-linear hierarchical data structure of nodes joined by directed edges (branches).

Binary Tree TraversalsBinary Tree Traversals

1. Tree Terminology & Binary Tree Properties

  • Root: Unique top node (Indegree = 0); every other node has Indegree = 1.
  • Leaf (External) Node: Node with Outdegree = 0 (no children).
  • Internal Node: Node with at least one child.
  • Level & Height: Root is at Level 0; Height (H) = Max Level + 1.
  • Types of Binary Trees:
  • Strictly (Full) Binary Tree: Every node has 0 or 2 children.
  • Complete Binary Tree: All levels are completely filled except possibly the last, which is filled left-to-right.
  • Extended Binary Tree (2-Tree): Replaces every NULL link with an external node; satisfies E = I + 2N (external path length vs internal path length).
  • Mathematical Bounds (for N nodes, height H):
  • Hmin = ⌊ log2 N ⌋ + 1 (complete tree), Hmax = N (skewed tree)
  • Nmin = H, Nmax = 2H - 1

Sequential Array Representation

  • 1-based indexing: Parent at k ⇒ Left = 2k, Right = 2k + 1, Parent = ⌊ k/2 ⌋.
  • 0-based indexing: Parent at k ⇒ Left = 2k + 1, Right = 2k + 2, Parent = ⌊ (k-1)/2 ⌋.

2. Tree Traversals (Recursive & Iterative)

  1. Preorder (NLR): Node → Left → Right.
  • Iterative (1 Stack): Push root; while stack non-empty, pop u, print u, push u->right then u->left (so Left is popped first!).
  1. Inorder (LNR): Left → Node → Right. (Yields sorted order in a BST!)
  • Iterative (1 Stack): Push left spine (curr = curr->left), pop u, print u, set curr = u->right.
  1. Postorder (LRN): Left → Right → Node.
  • Iterative (2 Stacks): Run modified Preorder (N R L) pushing onto Stack2, then pop all of Stack2!
  1. Level-Order (BFS): Visit level by level using a Queue.

3. Tree Reconstruction Worked Example (CIC-209 Deck)

Given Preorder: A B D E F C G H J L K and Inorder: D B F E A G C L J H K:

  1. First element of Preorder is A → Root = A.
  2. Split Inorder around A: Left subtree = D B F E, Right subtree = G C L J H K.
  3. Next in Preorder is B (root of left) with Inorder D | B | F E → D is left child; E is right child with left child F.
  4. Right subtree root is C with Inorder G | C | L J H K → G is left child; H is right child with J (left child L) and K.

4. Expression Trees

Internal nodes hold operators, leaves hold operands. For (a - b) / ((c * d) + e):

  • Postorder (Postfix): a b - c d * e + /
  • Construction from Postfix: Scan left-to-right; push operand nodes onto a stack; on operator, pop two subtrees (right, then left), attach as children, and push the new subtree!

More Tree Terminology (from the notes)

Using the tree rebuilt in the worked example below-A(B(D, E(F)), C(G, H(J(L), K))):

TermMeaningIn the example
Degree of a nodeNumber of children (subtrees)deg(A) = 2, deg(E) = 1, deg(D) = 0
Degree of a treeMaximum degree of any node2 (it is a binary tree)
Indegree / outdegreeEdges coming in / going out (directed view)Root A has indegree 0; every other node has indegree 1; outdegree = degree
Leaf (terminal)Node of degree 0D, F, G, L, K
Internal nodeNode with at least one childA, B, C, E, H, J
SiblingsChildren of the same parent(B, C), (D, E), (G, H), (J, K)
Ancestors of XAll nodes on the path from root to XAncestors of L: J, H, C, A
Descendants of XAll nodes in X's subtreeDescendants of C: G, H, J, L, K
Level / depthRoot at level 0, children at level 1, …L is at level 4
Height of treeNumber of edges on the longest root-to-leaf path4 (A → C → H → J → L)

Iterative Traversals Using an Explicit Stack

Preorder (iterative)

TEXT
push(root)
while stack not empty:
    node = pop()
    visit(node)
    if node.right: push(node.right)   // right first so that left is processed first
    if node.left:  push(node.left)

Inorder (iterative)

TEXT
cur = root
while cur != NULL or stack not empty:
    while cur != NULL:      // go as far left as possible
        push(cur); cur = cur.left
    cur = pop()
    visit(cur)
    cur = cur.right

Level order (BFS) - enqueue root; repeat: dequeue a node, visit it, enqueue its left then right child, until the queue is empty. For the example tree: A B C D E G H F J K L.

Reconstruction from Inorder + Postorder (notes' second version)

Inorder: D B F E A G C L J H K, Postorder: D F E B G L J K H C A

  1. The last postorder element is the root → A. Inorder splits into left D B F E and right G C L J H K.
  2. Postorder of the left part is D F E B → its root is B (last). Inorder D | B | F E → D is B's left child; right part F E has postorder F E → root E with left child F.
  3. Postorder of the right part is G L J K H C → root C. Inorder G | C | L J H K → G is C's left child.
  4. Right of C: inorder L J H K, postorder L J K H → root H; inorder L J | H | K → K is H's right child; L J with postorder L J → root J with left child L.
TEXT
            A
         /     \
        B       C
       / \     / \
      D   E   G   H
         /       / \
        F       J   K
               /
              L

Both pairs (preorder + inorder, or postorder + inorder) give the same tree. Preorder + postorder alone is not enough to fix a unique binary tree.

Writing an Expression Tree Back as Infix

An inorder traversal of an expression tree gives the infix form, but the brackets are lost. To restore them, print ( before visiting a non-leaf node's left subtree and ) after its right subtree:

C
void infix(Node *t) {
    if (t == NULL) return;
    if (t->left) printf("(");
    infix(t->left);
    printf("%c", t->data);
    infix(t->right);
    if (t->left) printf(")");
}

For the tree of (a + b) * (c − d) this prints ((a+b)*(c-d)); preorder gives the prefix * + a b − c d and postorder the postfix a b + c d − *.

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Explain Preorder, Inorder, Postorder, and Level-Order traversals of a Binary Tree with iterative algorithms. (7.5 Marks)
  • Write: NLR / LNR / LRN / BFS definitions, recursive + stack/queue iterative steps, and a worked tree diagram showing all 4 traversal outputs.
  • Q2. Reconstruct the Binary Tree from Preorder A B D E F C G H J L K and Inorder D B F E A G C L J H K. (5 Marks)
  • Write: Root selection from Preorder, left/right subtree splitting from Inorder, and draw the final tree.