Tree Terminology Root Leaf Height Depth Level in DSA Typescript - Time & Space Complexity
When working with trees, it is important to understand how the time to visit nodes grows as the tree gets bigger.
We want to know how operations like finding height or depth take longer as the tree size increases.
Analyze the time complexity of the following code snippet.
function treeHeight(node: TreeNode | null): number {
if (node === null) return -1;
const leftHeight = treeHeight(node.left);
const rightHeight = treeHeight(node.right);
return 1 + Math.max(leftHeight, rightHeight);
}
This code calculates the height of a 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 the height.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
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 is constant time."
[OK] Correct: Even though height is about the longest path, the function must check every node to be sure, so it visits all nodes.
Understanding how tree operations scale helps you explain your approach clearly and shows you know how data size affects performance.
"What if we changed the tree to be a linked list (all nodes have only one child)? How would the time complexity change?"