Tree Terminology Root Leaf Height Depth Level in DSA Javascript - Time & Space Complexity
We want to understand how the time to explore a tree changes as the tree grows.
How does the number of steps grow when we visit nodes like root, leaves, or measure height and depth?
Analyze the time complexity of the following code snippet.
function treeHeight(node) {
if (!node) return -1;
const leftHeight = treeHeight(node.left);
const rightHeight = treeHeight(node.right);
return Math.max(leftHeight, 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 tree grows, the function visits every node once to find height.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The number of steps grows directly with the number of nodes.
Time Complexity: O(n)
This means the time to find height grows linearly with the number of nodes in the tree.
[X] Wrong: "The height calculation only depends on the longest path, so it takes less time than visiting all nodes."
[OK] Correct: Even to find the longest path, the function must check every node to be sure no longer path exists.
Understanding how tree operations scale helps you explain your approach clearly and confidently in interviews.
"What if we changed the tree to a linked list (all nodes have only one child)? How would the time complexity change?"