Binary Tree

Context: FIT1008_MOC · a Tree where each node has children · backbone clustering Traversal (pre/in/post/level) and the Expression Tree specialisation · a complete one is a Heap

Quick Revision

  • 🎯 Objective: tree with ≤ 2 children per node ➔ ops are , so balance decides vs .
  • 📦 Core Components: shape families ➔ full/complete/perfect/balanced | traversals ➔ pre/in/post (DFS) + level (BFS) | Expression Tree ➔ operators inner, operands leaves.
  • ⚡ Key Constraint: all traversals ; structural ops balanced, degenerate (sorted-input “stick”).

📝 Core

1. The Binary Tree (Shape & Balance)

  • Structure ➔ each node has left, right links to child nodes; ops cost .
  • Shape familiesfull (0/2 children) | complete (last level filled left = Heap shape) | perfect () | balanced (heights differ ).
  • Balance dependency ➔ same keys form wildly different heights by insertion order; sorted input ➔ height- stick (, like a LinkList).

2. Traversals (DFS + BFS)

  • DFS orderspreorder (root,L,R) | inorder (L,root,R) | postorder (L,R,root) — differ only in when the root is processed.
  • Level-order ➔ BFS by levels using a Queue (ADT).
  • Uses + reconstruction ➔ preorder serialises; inorder of a BST = sorted; postorder = RPN/free; (pre+in) or (post+in) is unique, pre+post is not.

3. Expression Tree (Parse Tree)

  • Structureoperands = leaves, operators = inner nodes; compilers build them.
  • Notation by traversal ➔ preorder→prefix | inorder→infix (drops brackets) | postorder→postfix/RPN.
  • Ordering principle ➔ by expression structure, not by key (unlike a Binary Search Tree (BST)).

⚙️ Core Implementation

🔹 Node + recursive size

🔹 Traversals (recursive DFS + queue-based BFS)

🔹 Expression Tree — traversal ⟷ notation

⚖️ Core Decision Matrix

AspectCost / ResultTrigger / Note
structural op (balanced)height
structural op (degenerate)sorted input → “stick”
any traversaleach node once, best = worst
DFS recursion space balanced / degenerate
BFS (level-order) spaceup to at widest level
Morris inorder spacetemporary link threading

When It Flips: balance is the whole game — without it, sorted/adversarial input ➔ height- stick ➔ . Specialisations: Binary Search Tree (BST) (key order → search), Expression Tree (structure order → notation), and a complete + heap-ordered tree is a Heap.

📊 Exam Execution Trace

Manual Execution Trace

Traversals of the BST 4(2(1,3), 6(5,7)):

Step / StateTrigger OpOrderSequence Payload
0 (Init)tree4(2(1,3), 6(5,7))
1preorderroot,L,R4, 2, 1, 3, 6, 5, 7
2inorderL,root,R1, 2, 3, 4, 5, 6, 7 (sorted ✓)
3postorderL,R,root1, 3, 2, 5, 7, 6, 4
4level-orderby level4, 2, 6, 1, 3, 5, 7

Applied Exercise

Problem: Reconstruct a tree from preorder [4,2,1,3,6,5,7] + inorder [1,2,3,4,5,6,7]. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: preorder fixes roots, inorder splits subtrees ⟹ unique tree; pre+post alone is not unique.

🧠 Active Recall