Tree Traversal Preorder Root Left Right in DSA C++ - 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.
void preorderTraversal(Node* root) {
if (root == nullptr) return;
visit(root); // Process current node
preorderTraversal(root->left); // Traverse left subtree
preorderTraversal(root->right); // Traverse right subtree
}
This code visits each node in the tree starting from the root, then left child, then right child.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node once (the
visit(root)call). - How many times: Exactly once per node in the tree.
As the number of nodes (n) increases, the number of visits grows directly with n.
| 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: "Preorder traversal takes more time because it visits nodes multiple times."
[OK] Correct: Each node is visited exactly once, so the time depends only on the number of nodes, not repeated visits.
Understanding preorder traversal time helps you explain how tree algorithms scale and shows you can analyze recursive code clearly.
"What if we changed preorder traversal to inorder traversal? How would the time complexity change?"