Inorder traversal gives sorted order in Data Structures Theory - Time & Space Complexity
We want to understand how the time needed to traverse a binary search tree in order grows as the tree gets bigger.
Specifically, how does the number of steps change when we do an inorder traversal to get sorted values?
Analyze the time complexity of the following inorder traversal code.
function inorderTraversal(node) {
if (node == null) return;
inorderTraversal(node.left);
visit(node.value); // process current node
inorderTraversal(node.right);
}
This code visits each node in a binary search tree in ascending order.
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 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 as the tree size grows.
Time Complexity: O(n)
This means the time to complete the traversal grows directly with the number of nodes in the tree.
[X] Wrong: "Inorder traversal takes longer because it visits nodes multiple times."
[OK] Correct: Each node is visited exactly once during inorder traversal, so the time grows linearly, not more.
Knowing that inorder traversal visits each node once helps you explain how to get sorted data from a binary search tree efficiently.
"What if the tree is not a binary search tree but just any binary tree? How would the time complexity of inorder traversal change?"