Height of Binary Tree in DSA C++ - Time & Space Complexity
We want to understand how long it takes to find the height of a binary tree as the tree grows.
How does the time needed change when the tree has more nodes?
Analyze the time complexity of the following code snippet.
int height(Node* root) {
if (root == nullptr) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
This code finds the height of a binary tree by checking the height of left and right subtrees recursively.
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 once, so the time grows 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 find the height grows in direct proportion to the number of nodes in the tree.
[X] Wrong: "The height calculation only depends on the longest path, so it should be faster than visiting all nodes."
[OK] Correct: To find the longest path, the function must check every node to be sure no taller path exists, so it visits all nodes.
Understanding this helps you explain how recursive tree algorithms work and why visiting all nodes is often necessary.
"What if the tree was a balanced binary tree? How would the time complexity change?"