COMP1010 Week 11

Course Announcements and Academic Context

  • COMP1010 Schedule:
    • Week 11 covers the final examinable content for the course, focusing on advanced recursive data structures.
    • Week 12 focuses on practical applications and synthesizing course topics.
    • Week 13 features an industry guest lecture.
  • Week 13 Industry Guest Speaker:
    • Speaker: Daniel Sutancier (also referred to as Dennis Santo).
    • Background: Completed PhD at Macquarie University between 2005 and 2008 (concluding around 2010). Worked as a university Teaching Assistant (TA) for approximately 10 years before transitioning to the fintech sector, where he has worked for 5 to 6 years.
    • Productivity: Delivers an output comparable to an entire corporate development team of 4 to 5 engineers.
    • Lecture Topic: The day-to-day application of agentic AI within the software development industry, analyzing industry expectations and skill requirements projected over the next 3 to 5 years.
  • Assessment Guidance & Module Quiz Strategy:
    • Recursive data structures constitute the core of the module quiz.
    • Skills Lab Re-attempt: Understanding memory diagrams enables eligible students taking the supplementary skills lab attempt during the final examination period to obtain an additional 10 out of 100 marks (equivalent to 4 out of 40 scaled marks), which directly affects the passing threshold.
    • Time Management Strategy: The module quiz contains 15 questions across 90 to 100 minutes (an average of 6 minutes per question). A recommended strategy is prioritizing the first 10 questions, which account for 75 out of 100 total marks. This allows 9 minutes per question, easing cognitive load, before attempting advanced questions 11 through 15.
    • Pass and credit level questions are restricted to basic recursive data structures and linear memory diagrams; distinction and high distinction questions assess complex configurations and multi-step recursive algorithms.

Memory Diagram Fundamentals: References vs. Instances

  • Core Prerequisites for Recursive Data Structures:
    • Distinguishing between an instance and a reference.
    • Understanding class composition.
  • Diagrammatic Rules for References and Instances:
    • Instances: Represented by any entity receiving an incoming arrow (→Instance\rightarrow \text{Instance}).
    • References: Represented by any variable or field initiating an outgoing arrow (Reference→\text{Reference} \rightarrow).
    • Type Homogeneity: A reference of type XX strictly references an instance of type XX. A Line reference refers exclusively to a Line instance; a Point reference refers exclusively to a Point instance; a Node reference refers exclusively to a Node instance.

In-Place vs. Out-of-Place Algorithms

  • Out-of-Place Algorithms:
    • Definition: Algorithms that process data structures by allocating new objects and data structures rather than modifying existing ones.
    • Advantage: State preservation. The original data structure remains unmodified and intact.
    • Disadvantage: Increased memory and allocation overhead (O(n)O(n) additional space).
    • Domain Application: Crucial in cybersecurity and digital forensics, where original physical evidence (hard drives, thumb drives, disk images) must never be manipulated directly, requiring operations to run on cloned duplicates.
  • In-Place Algorithms:
    • Definition: Algorithms that operate directly on existing nodes and reference links without allocating substantial new data structures or object instances. Minor temporary variables (e.g., variables used for reference swaps) are permitted.
    • Advantage: Memory efficiency (O(1)O(1) auxiliary heap allocation).
    • Disadvantage: Destruction of original state; previous structural connections cannot be recaptured once references are overwritten.

Recursive Odd Item Removal: Out-of-Place Implementation

  • Algorithmic Behavior:
    • Given an input list such as [1, 10, 2, 6, 19], the resulting list retains only even elements ([10, 2, 6]), while the original linked list remains completely intact in memory.
  • Recursive Step Logic:
    • Inspect start.data.
    • Odd Case: If start.data % 2 != 0, discard the current node from the output. Return the result of the recursive sub-call on the rest of the list: removeOdds(start.next).
    • Even Case: If start.data % 2 == 0, allocate a new Node instance holding start.data whose next attribute references the result of the recursive call on the tail of the list.
  • Java Code Implementation:java Node oddsRemovedFromRemainingList = removeOdds(start.next); Node result = new Node(start.data, oddsRemovedFromRemainingList); return result;     
  • Concrete Trace Example:
    • Input list: 10 -> 7 -> 19 -> 4 -> 16 -> 4 -> 10 -> 14.
    • Node 10 is even: delegation executes removeOdds(start.next) on node 7.
    • The recursive sub-call processes the sub-list starting at 7, returning a processed chain: 4 -> 16 -> 4 -> 10 -> 14.
    • The caller instantiates a brand-new node containing data 10 and links its next pointer to node 4.

Recursive Odd Item Removal: In-Place Implementation

  • Algorithmic Mechanics:
    • No calls to new Node(...) are permitted; operations rely strictly on modifying existing reference links (start.next).
  • Method Implementation:java public static Node removeOdds(Node start) { if (start == null) { return null; } if (start.data % 2 != 0) { return removeOdds(start.next); } else { start.next = removeOdds(start.next); return start; } }     
  • Step-by-Step Execution Trace (A(10)→B(7)→C(2)→D(9)→nullA(10) \rightarrow B(7) \rightarrow C(2) \rightarrow D(9) \rightarrow \text{null}):
    • Call 1 (removeOdds(A)): A is not null. 10 % 2 == 0 (even). Evaluates else branch: A.next = removeOdds(B). Call put on hold.
    • Call 2 (removeOdds(B)): B is not null. 7 % 2 != 0 (odd). Evaluates if branch: returns removeOdds(C). Call put on hold.
    • Call 3 (removeOdds(C)): C is not null. 2 % 2 == 0 (even). Evaluates else branch: C.next = removeOdds(D). Call put on hold.
    • Call 4 (removeOdds(D)): D is not null. 9 % 2 != 0 (odd). Evaluates if branch: returns removeOdds(null). Call put on hold.
    • Call 5 (removeOdds(null)): Base case reached. Returns null.
    • Unwinding Call 4: Receives null and returns null to Call 3.
    • Unwinding Call 3: C.next is assigned null. Call 3 returns reference copy of C to Call 2.
    • Unwinding Call 2: Call 2 directly returns the reference copy of C to Call 1.
    • Unwinding Call 1: A.next is assigned C. Call 1 returns reference copy of A.
  • Final Structure: A(10) -> C(2) -> null.
  • Hypothetical Alternative Scenario:
    • If node A held an odd integer (e.g., 13), removeOdds(A) would skip the else branch and directly return removeOdds(B), which evaluates to C(2). The method returns the address of the first non-odd node directly.
  • Java Garbage Collection:
    • Because A.next was reassigned directly to C, the incoming reference to node B(7) dropped to zero. Node C.next was set to null, dropping the incoming reference to node D(9) to zero.
    • Unreferenced heap instances are automatically detected and erased from memory by the Java Garbage Collector.

In-Place Singly Linked List Reversal

  • Attribution & Background: Refined recursive algorithm by student Xinyu Kai (Ara), simplifying redundant branching conditions present in older iterations.
  • Conceptual Objective: Reverse the internal reference directions of a singly linked list [1 -> 7 -> 2 -> 9 -> null] to [9 -> 2 -> 7 -> 1 -> null] in place without instantiating new Node objects.
  • Java Code Implementation:java public static Node reverse(Node start) { if (start == null || start.next == null) { return start; } Node revRest = reverse(start.next); start.next.next = start; start.next = null; return revRest; }     
  • Key Operations:
    • Base Case: A list with 0 nodes (start == null) or 1 node (start.next == null) is already reversed; returning start leaves it unchanged.
    • Recursive Sub-call ("Leap of Faith"): Assume reverse(start.next) correctly reverses nodes from start.next to the end, returning the new head of the reversed sublist (revRest).
    • The Reconnect Step (start.next.next = start): Because start.next still points to the adjacent node in the forward chain, setting start.next.next = start makes the adjacent node point backwards to start.
    • Loop Severing (start.next = null): Clears the forward pointer of start to prevent a circular reference between the two nodes.
    • Return Statement: Returns revRest (not start), propagating the head of the newly reversed chain up the call stack.
  • Execution Trace (A(1)→B(7)→C(2)→D(9)→nullA(1) \rightarrow B(7) \rightarrow C(2) \rightarrow D(9) \rightarrow \text{null}):
    • reverse(A) calls reverse(B) calls reverse(C) calls reverse(D).
    • reverse(D): D.next == null, hits base case, returns reference copy of D.
    • Execution on C (start=C\text{start} = C):
      • revRest receives D.
      • C.next.next = C assigns D.next = C.
      • C.next = null breaks the forward link from C to D.
      • Returns D.
    • Execution on B (start=B\text{start} = B):
      • revRest receives D.
      • B.next.next = B assigns C.next = B.
      • B.next = null breaks the forward link from B to C.
      • Returns D.
    • Execution on A (start=A\text{start} = A):
      • revRest receives D.
      • A.next.next = A assigns B.next = A.
      • A.next = null breaks the forward link from A to B.
      • Returns D.
    • Resulting Sequence: D(9) -> C(2) -> B(7) -> A(1) -> null.

Memory Diagram Construction and Tracing

  • Diagramming Software: Tool demonstrated is draw.io (redirects to appapp.diagram.net). Mid-semester and final examination assessments require manual drawing on paper.
  • Complex Graph Evaluation Example:java Node a = new Node(10, null); Node b = new Node(70, null); Node c = new Node(20, null); Node d = new Node(90, null); a.next = b; d.next = c; c.next = a.next;     
    • Step-by-step Pointer Tracing:
      • a references instance 10, with a.next pointing to b (70).
      • d references instance 90, with d.next pointing to c (20).
      • a.next evaluates to reference b (70). Therefore, c.next = a.next assigns c.next to point directly to b (70).
    • Structural Property Analysis: This configuration does not form a linear linked list. Node b possesses two incoming references (from a and c). The structure represents a directed, acyclic, non-connected graph.
  • Nested Instantiation Evaluation:java Node x = new Node(7, new Node(8, new Node(6, null)));     
  • Evaluation Order: Evaluated from the inside out:
    1. new Node(6, null) creates an instance with data = 6, next = null.
    2. new Node(8, <ref to 6>) creates an instance with data = 8, next referencing node 6.
    3. new Node(7, <ref to 8>) creates an instance with data = 7, next referencing node 8.
    4. x stores the reference to node 7.
  • Component Classification: x is a Node reference; internal link variables are Node references; the allocated blocks containing values 7, 8, and 6 are Node instances.

Doubly Linked Lists (DNode)

  • Moving Beyond Primitive Payloads:
    • Node contents are not limited to primitive integers; nodes can encapsulate reference types, including complex composite objects.
  • Composite Class Specifications:java public class Line { public Point start; public Point end; } &nbsp;&nbsp;&nbsp;&nbsp;
    • Line a = new Line(new Point(1, 7), new Point(2, 9));
    • Line b = new Line(new Point(6, 1), new Point(7, 4));
    • Line c = new Line(new Point(10, 0), new Point(3, 0)); (Represents a horizontal line where yy remains 00 while xx varies).
  • Doubly Linked Node (DNode) Architecture:
    • Three instance variables: payload (holds an object reference, e.g., Line), previous (holds a DNode reference), and next (holds a DNode reference).
    • Constructor signature: public DNode(Line payload, DNode previous, DNode next).
  • Bidirectional Integrity Rule:
    • Every forward assignment requires a corresponding backward assignment:
    • x.next = y; requires y.previous = x;.
    • y.next = z; requires z.previous = y;.
  • Head and Tail Reference Maintenance:
    • A doubly linked list typically maintains references to both ends: head (the first node) and tail (the last node).
    • Forward traversal begins at head and advances via .next.
    • Backward traversal begins at tail and advances via .previous.
    • Useful in statistical distribution analysis, such as evaluating data sets where target percentiles or medians reside near specific boundaries.

Binary Trees (BNode)

  • Structural Comparison with Doubly Linked Lists:

    • Like a DNode, a binary tree node contains two reference variables: left and right.
    • Unlike a doubly linked list, links are hierarchical and strictly unidirectional (parent to child). Standard tree nodes do not maintain a backward reference to the parent.
    • The entry point to a tree is conventionally designated as root.
  • Tree Navigation Trace:

    • Structure:
      • Root: 50
      • Left child of 50: 10
      • Right child of 50: 70
      • Left child of 10: 80
      • Right child of 10: 20
      • Left child of 70: null
      • Right child of 70: 60
      • Left child of 60: 5
      • Right child of 60: null
    • Navigation Paths:
      • Reaching 80: root.left.left
      • Reaching 20: root.left.right
      • Reaching 5: root.right.right.left
  • Binary Tree Height:

    • Definition: The maximum number of nodes along the longest path from the root down to a leaf node.
    • Example Path Calculation: Longest path contains nodes 50 -> 70 -> 60 -> 5, producing a height of 4. (If node 5 were removed, the longest paths would be 50-10-80, 50-10-20, and 50-70-60, all having a height of 3).
    • Recursive Height Implementation:java public static int height(BNode root) { if (root == null) { return 0; } int lh = height(root.left); int rh = height(root.right); return Math.max(lh, rh) + 1; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  • Alternative Convoluted One-Liner:java public static int height(BNode root) { if (root == null) return 0; return Math.max(height(root.left) + 1, height(root.right) + 1); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Finding the Maximum Value (highest):

    • Return Type Consideration: Returning a primitive int default (such as 0 for root == null) introduces logic bugs in trees containing negative values (e.g., a node with -5 comparing against base case 0 would incorrectly return 0). Thus, the method returns an Integer object wrapper, returning null when root == null.

    • Recursive Highest Implementation: ```java public static Integer highest(BNode root) { if (root == null) { return null; } Integer highestLeft = highest(root.left); Integer highestRight = highest(root.right);

      if (highestLeft != null && highestRight != null) {
          return Math.max(root.data, Math.max(highestLeft, highestRight));
      }
      if (highestLeft != null) {
          return Math.max(root.data, highestLeft);
      }
      if (highestRight != null) {
          return Math.max(root.data, highestRight);
      }
      return root.data;
      

      }         ```

  • In the example tree, highest(root) yields 80, whereas the minimum value is 5.

Questions & Discussion

  • Recursion vs. Iteration Overhead:
    • Question: Why use recursion over linked lists when iteration can perform the same tasks without function call overhead?
    • Response: Recursion incurs function call overhead and stack consumption, making it more expensive than iteration on linked lists. However, recursion offers high intuitive elegance and algorithmic simplicity. Through the "leap of faith" (delegation), the programmer processes the immediate node while delegating the entire remainder of the sequence to sub-calls without managing explicit loop indices or state tracking variables.
  • In-Place Odd Removal Reference Severing:
    • Question: In the in-place odd removal trace, after disconnecting node B(7) by pointing A(10) to C(2), wouldn't node C(2) still refer to D(9)?
    • Response: No. When the recursive call on node C executed (removeOdds(C)), C.next was explicitly assigned to the result of removeOdds(D). Since D contained an odd value (9), its call returned null (the result of removeOdds(null)). Consequently, C.next was updated to null, severing the link between C and D.