Tree Traversal Inorder Left Root 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 the time to do an inorder traversal change with the number of nodes?
Analyze the time complexity of the following code snippet.
// Inorder traversal: Left, Root, Right
func inorderTraversal(root *TreeNode) {
if root == nil {
return
}
inorderTraversal(root.Left)
fmt.Println(root.Val)
inorderTraversal(root.Right)
}
This code visits every node in a binary tree in the order: left child, node itself, then right child.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Exactly once per node in the tree.
Each node is visited once, 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 in proportion to the number of nodes.
[X] Wrong: "The recursion makes this traversal take more than linear time because it calls itself many times."
[OK] Correct: Each node is visited only once, so the total work is still proportional to the number of nodes, not more.
Understanding this traversal's time helps you explain how tree operations scale, a key skill for many coding problems.
"What if we changed inorder traversal to preorder traversal? How would the time complexity change?"