Tree Traversal Preorder Root Left Right in DSA Go - Time & Space Complexity
We want to understand how the time needed to visit all nodes in a tree grows as the tree gets bigger.
Specifically, we ask: How does preorder traversal scale with the number of nodes?
Analyze the time complexity of the following code snippet.
func preorder(root *Node) {
if root == nil {
return
}
fmt.Println(root.value) // Visit root
preorder(root.left) // Traverse left subtree
preorder(root.right) // Traverse right subtree
}
This code visits each node starting from the root, then left child, then right child recursively.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node once (printing value).
- How many times: Exactly once per node in the tree.
As the number of nodes grows, the number of visits grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 visits |
| 100 | 100 visits |
| 1000 | 1000 visits |
Pattern observation: The operations grow linearly with the number of nodes.
Time Complexity: O(n)
This means the time to complete preorder traversal grows directly in 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 work is proportional to the number of nodes, not more.
Understanding preorder traversal time helps you explain how tree algorithms scale and shows you can analyze recursive code clearly.
"What if we changed preorder to inorder traversal? How would the time complexity change?"