Tree vs Array vs Linked List When Hierarchy Matters in DSA Typescript - Complexity Comparison
When working with data that has a hierarchy, like family trees or company structures, choosing the right data structure matters.
We want to understand how fast we can find or visit elements depending on the structure used.
Analyze the time complexity of traversing hierarchical data stored in different structures.
// Tree node definition
class TreeNode {
value: number;
children: TreeNode[];
constructor(value: number) {
this.value = value;
this.children = [];
}
}
// Function to traverse tree
function traverseTree(node: TreeNode | null): void {
if (!node) return;
console.log(node.value);
for (const child of node.children) {
traverseTree(child);
}
}
This code visits every node in a tree, printing its value and then visiting its children recursively.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Once per node in the tree.
As the number of nodes grows, the time to visit all nodes grows proportionally.
| Input Size (n nodes) | Approx. Operations (visits) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The time grows linearly with the number of nodes.
Time Complexity: O(n)
This means visiting all nodes takes time proportional to the number of nodes.
[X] Wrong: "Using an array or linked list to represent hierarchy is always faster."
[OK] Correct: Arrays and linked lists do not naturally represent parent-child links, so finding children can take extra time, making traversal slower.
Understanding how different structures handle hierarchy helps you choose the right tool and explain your choices clearly in interviews.
"What if we stored the hierarchy in a flat array with parent indexes? How would the time complexity of traversal change?"
Practice
Solution
Step 1: Understand hierarchy representation
Hierarchies have parent-child relationships, which are naturally modeled by trees.Step 2: Compare data structures
Arrays and linked lists are linear and do not represent branching well, unlike trees.Final Answer:
Tree -> Option AQuick Check:
Hierarchy = Tree [OK]
- Choosing Array because it's simple
- Choosing Linked List thinking it can represent hierarchy
- Confusing Stack with hierarchical structure
Solution
Step 1: Check next pointer type
Next pointer should allow either another Node or null to mark list end.Step 2: Verify constructor initialization
Constructor sets value and initializes next to null correctly.Final Answer:
class Node { value: number; next: Node | null; constructor(value: number) { this.value = value; this.next = null; } } -> Option BQuick Check:
Next pointer = Node or null [OK]
- Not allowing null for next pointer
- Initializing next as undefined instead of null
- Using any type which loses type safety
class TreeNode {
value: number;
children: TreeNode[];
constructor(value: number) {
this.value = value;
this.children = [];
}
}
const root = new TreeNode(1);
const child1 = new TreeNode(2);
const child2 = new TreeNode(3);
root.children.push(child1, child2);
console.log(root.children.map(c => c.value));Solution
Step 1: Understand tree structure
Root node has value 1 and two children with values 2 and 3.Step 2: Analyze console.log output
Mapping children array extracts values [2, 3], root's value 1 is not included.Final Answer:
[2, 3] -> Option DQuick Check:
Children values = [2, 3] [OK]
- Including root value in output
- Expecting nested arrays instead of flat array
- Assuming children is not iterable
class Node {
value: number;
next: Node | null;
constructor(value: number) {
this.value = value;
this.next = null;
}
}
const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
let current = head;
while (current !== null) {
console.log(current.value);
current = current.next.next;
}Solution
Step 1: Trace the while loop iteration
Loop moves current by current.next.next, skipping nodes and risking null access.Step 2: Identify null pointer risk
When current.next is null, accessing current.next.next causes runtime error.Final Answer:
Accessing next.next without checking if next is null -> Option CQuick Check:
Null check missing before next.next access [OK]
- Ignoring null checks causing runtime errors
- Thinking constructor syntax is wrong
- Believing console.log causes errors
Solution
Step 1: Analyze the problem requirements
Organizational chart has hierarchy with employees having multiple direct reports (children).Step 2: Match data structure to hierarchy
Tree structure supports nodes with multiple children, representing managers and their reports well.Step 3: Evaluate other options
Array and linked list are linear and do not represent branching; stack is for LIFO, not hierarchy.Final Answer:
Tree, because it naturally models hierarchical relationships with multiple children -> Option AQuick Check:
Hierarchy with multiple children = Tree [OK]
- Choosing Array for hierarchy
- Thinking Linked List handles multiple children well
- Confusing Stack with hierarchical data
Ready to prove it?
Pass the test and this pattern moves unknown
