Tree Traversal Preorder Root Left 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 preorderTraversal(root: TreeNode | null): number[] {
if (root === null) return [];
const left = preorderTraversal(root.left);
const right = preorderTraversal(root.right);
return [root.val, ...left, ...right];
}
This code visits each node in a tree starting from the root, then left child, then right child, collecting values in that order.
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.
Each node is visited exactly once, so the 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 time grows linearly as the tree size increases.
Time Complexity: O(n)
This means the time to complete the traversal grows in direct proportion to the number of nodes.
[X] Wrong: "Preorder traversal takes more than linear time because it visits nodes multiple times."
[OK] Correct: Each node is visited exactly once, so the total steps grow only with the number of nodes, not more.
Understanding preorder traversal time helps you explain how tree algorithms scale, a key skill in many coding challenges.
"What if we changed preorder traversal to inorder traversal? How would the time complexity change?"