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 ().
- References: Represented by any variable or field initiating an outgoing arrow ().
- Type Homogeneity: A reference of type strictly references an instance of type . A
Linereference refers exclusively to aLineinstance; aPointreference refers exclusively to aPointinstance; aNodereference refers exclusively to aNodeinstance.
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 ( 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 ( 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.
- Given an input list such as
- 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 newNodeinstance holdingstart.datawhosenextattribute references the result of the recursive call on the tail of the list.
- Inspect
- 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
10is even: delegation executesremoveOdds(start.next)on node7. - 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
10and links itsnextpointer to node4.
- Input list:
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).
- No calls to
- 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 ():
- Call 1 (
removeOdds(A)):Ais notnull.10 % 2 == 0(even). Evaluateselsebranch:A.next = removeOdds(B). Call put on hold. - Call 2 (
removeOdds(B)):Bis notnull.7 % 2 != 0(odd). Evaluatesifbranch: returnsremoveOdds(C). Call put on hold. - Call 3 (
removeOdds(C)):Cis notnull.2 % 2 == 0(even). Evaluateselsebranch:C.next = removeOdds(D). Call put on hold. - Call 4 (
removeOdds(D)):Dis notnull.9 % 2 != 0(odd). Evaluatesifbranch: returnsremoveOdds(null). Call put on hold. - Call 5 (
removeOdds(null)): Base case reached. Returnsnull. - Unwinding Call 4: Receives
nulland returnsnullto Call 3. - Unwinding Call 3:
C.nextis assignednull. Call 3 returns reference copy ofCto Call 2. - Unwinding Call 2: Call 2 directly returns the reference copy of
Cto Call 1. - Unwinding Call 1:
A.nextis assignedC. Call 1 returns reference copy ofA.
- Call 1 (
- Final Structure:
A(10) -> C(2) -> null. - Hypothetical Alternative Scenario:
- If node
Aheld an odd integer (e.g.,13),removeOdds(A)would skip theelsebranch and directly returnremoveOdds(B), which evaluates toC(2). The method returns the address of the first non-odd node directly.
- If node
- Java Garbage Collection:
- Because
A.nextwas reassigned directly toC, the incoming reference to nodeB(7)dropped to zero. NodeC.nextwas set tonull, dropping the incoming reference to nodeD(9)to zero. - Unreferenced heap instances are automatically detected and erased from memory by the Java Garbage Collector.
- Because
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 newNodeobjects. - 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; returningstartleaves it unchanged. - Recursive Sub-call ("Leap of Faith"): Assume
reverse(start.next)correctly reverses nodes fromstart.nextto the end, returning the new head of the reversed sublist (revRest). - The Reconnect Step (
start.next.next = start): Becausestart.nextstill points to the adjacent node in the forward chain, settingstart.next.next = startmakes the adjacent node point backwards tostart. - Loop Severing (
start.next = null): Clears the forward pointer ofstartto prevent a circular reference between the two nodes. - Return Statement: Returns
revRest(notstart), propagating the head of the newly reversed chain up the call stack.
- Base Case: A list with 0 nodes (
- Execution Trace ():
reverse(A)callsreverse(B)callsreverse(C)callsreverse(D).reverse(D):D.next == null, hits base case, returns reference copy ofD.- Execution on
C():revRestreceivesD.C.next.next = CassignsD.next = C.C.next = nullbreaks the forward link fromCtoD.- Returns
D.
- Execution on
B():revRestreceivesD.B.next.next = BassignsC.next = B.B.next = nullbreaks the forward link fromBtoC.- Returns
D.
- Execution on
A():revRestreceivesD.A.next.next = AassignsB.next = A.A.next = nullbreaks the forward link fromAtoB.- 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 toappapp.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:
areferences instance10, witha.nextpointing tob(70).dreferences instance90, withd.nextpointing toc(20).a.nextevaluates to referenceb(70). Therefore,c.next = a.nextassignsc.nextto point directly tob(70).
- Structural Property Analysis: This configuration does not form a linear linked list. Node
bpossesses two incoming references (fromaandc). The structure represents a directed, acyclic, non-connected graph.
- Step-by-step Pointer Tracing:
- Nested Instantiation Evaluation:
java Node x = new Node(7, new Node(8, new Node(6, null))); - Evaluation Order: Evaluated from the inside out:
new Node(6, null)creates an instance withdata = 6,next = null.new Node(8, <ref to 6>)creates an instance withdata = 8,nextreferencing node 6.new Node(7, <ref to 8>)creates an instance withdata = 7,nextreferencing node 8.xstores the reference to node 7.
- Component Classification:
xis aNodereference; internal link variables areNodereferences; the allocated blocks containing values 7, 8, and 6 areNodeinstances.
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; } 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 remains while varies).
- Doubly Linked Node (
DNode) Architecture:- Three instance variables:
payload(holds an object reference, e.g.,Line),previous(holds aDNodereference), andnext(holds aDNodereference). - Constructor signature:
public DNode(Line payload, DNode previous, DNode next).
- Three instance variables:
- Bidirectional Integrity Rule:
- Every forward assignment requires a corresponding backward assignment:
x.next = y;requiresy.previous = x;.y.next = z;requiresz.previous = y;.
- Head and Tail Reference Maintenance:
- A doubly linked list typically maintains references to both ends:
head(the first node) andtail(the last node). - Forward traversal begins at
headand advances via.next. - Backward traversal begins at
tailand advances via.previous. - Useful in statistical distribution analysis, such as evaluating data sets where target percentiles or medians reside near specific boundaries.
- A doubly linked list typically maintains references to both ends:
Binary Trees (BNode)
Structural Comparison with Doubly Linked Lists:
- Like a
DNode, a binary tree node contains two reference variables:leftandright. - 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.
- Like a
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
- Root:
- Navigation Paths:
- Reaching 80:
root.left.left - Reaching 20:
root.left.right - Reaching 5:
root.right.right.left
- Reaching 80:
- Structure:
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 be50-10-80,50-10-20, and50-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; }
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); } Finding the Maximum Value (
highest):Return Type Consideration: Returning a primitive
intdefault (such as0forroot == null) introduces logic bugs in trees containing negative values (e.g., a node with-5comparing against base case0would incorrectly return0). Thus, the method returns anIntegerobject wrapper, returningnullwhenroot == 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 pointingA(10)toC(2), wouldn't nodeC(2)still refer toD(9)? - Response: No. When the recursive call on node
Cexecuted (removeOdds(C)),C.nextwas explicitly assigned to the result ofremoveOdds(D). SinceDcontained an odd value (9), its call returnednull(the result ofremoveOdds(null)). Consequently,C.nextwas updated tonull, severing the link betweenCandD.
- Question: In the in-place odd removal trace, after disconnecting node