Tree Traversal Inorder Left Root Right in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to visit all nodes in a tree grows as the tree gets bigger.
How does the number of steps change when the tree has more nodes?
Analyze the time complexity of the following code snippet.
function inorderTraversal(node: TreeNode | null): void {
if (node === null) return;
inorderTraversal(node.left);
console.log(node.value);
inorderTraversal(node.right);
}
This code visits each node in the tree in the order: left child, then root, then right child.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls to visit each node once.
- How many times: Once per node in the tree.
Each node is visited exactly one time, so the total steps grow directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows in a straight line with the number of nodes.
Time Complexity: O(n)
This means the time to complete the traversal grows directly with the number of nodes in the tree.
[X] Wrong: "Since the function calls itself twice, the time complexity is exponential like O(2^n)."
[OK] Correct: Each node is visited only once, so the total work is just one visit per node, not doubling each time.
Understanding tree traversal time helps you explain how algorithms handle hierarchical data efficiently, a common skill in many coding challenges.
"What if we changed inorder traversal to preorder traversal? How would the time complexity change?"