Height of Binary Tree in DSA Go - Time & Space Complexity
We want to understand how long it takes to find the height of a binary tree as the tree grows bigger.
How does the time needed change when the tree has more nodes?
Analyze the time complexity of the following code snippet.
func height(root *Node) int {
if root == nil {
return 0
}
leftHeight := height(root.Left)
rightHeight := height(root.Right)
if leftHeight > rightHeight {
return leftHeight + 1
}
return rightHeight + 1
}
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.
As the number of nodes grows, the function visits each node once to calculate height.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls |
| 100 | About 100 calls |
| 1000 | About 1000 calls |
Pattern observation: The number of operations grows directly with the number of nodes.
Time Complexity: O(n)
This means the time to find the height grows linearly with the number of nodes in the tree.
[X] Wrong: "The height calculation only depends on the longest path, so it should be O(log n)."
[OK] Correct: Even though height is about the longest path, the function must visit every node to be sure, so it takes time proportional to all nodes.
Understanding this helps you explain how recursive tree algorithms work and why visiting all nodes is often necessary.
"What if we stored the height at each node during insertion? How would the time complexity of finding height change?"