Height of Binary Tree in DSA Java - Time & Space Complexity
We want to understand how the time to find the height of a binary 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.
public int height(TreeNode root) {
if (root == null) return 0;
int leftHeight = height(root.left);
int rightHeight = height(root.right);
return 1 + Math.max(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.
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 steps grows roughly in direct proportion to 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 takes O(log n) time."
[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, not just the longest path.
Understanding this helps you explain how recursive tree algorithms work and how their time depends on tree size, a common topic in interviews.
"What if the tree was a balanced binary search tree? How would the time complexity change?"
Practice
Solution
Step 1: Understand height definition
The height of a binary tree is the number of edges on the longest path from the root to a leaf.Step 2: Apply to single node tree
With only one node (root), the longest path has length 0 edges.Final Answer:
0 -> Option DQuick Check:
Single node tree height = 0 [OK]
- Thinking height is 1 for single node
- Confusing height with number of nodes
- Assuming height undefined for single node
Solution
Step 1: Check Java method syntax
Java methods must specify access modifier, return type, method name, and parameters correctly.Step 2: Validate each option
public int height(Node root) follows correct syntax: public int height(Node root). Others have syntax errors.Final Answer:
public int height(Node root) -> Option AQuick Check:
Correct Java method signature = public int height(Node root) [OK]
- Wrong order of return type and name
- Missing return type
- Using void with return value
class Node {
int data;
Node left, right;
Node(int d) { data = d; left = right = null; }
}
public class Test {
public static int height(Node root) {
if (root == null) return 0;
int leftHeight = height(root.left);
int rightHeight = height(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
System.out.println(height(root));
}
}Solution
Step 1: Visualize the tree structure
The tree has root 1, left child 2, right child 3, and left child of 2 is 4. The longest path is 1->2->4.Step 2: Calculate height recursively
Height is max depth: left subtree height = 2 (nodes 2->4), right subtree height = 1 (node 3), so total height = max(2,1)+1 = 3.Final Answer:
3 -> Option BQuick Check:
Longest path length = 3 [OK]
- Counting edges instead of nodes
- Ignoring null child base case
- Misreading tree structure
public int height(Node root) {
if (root == null) {
return -1;
}
int leftHeight = height(root.left);
int rightHeight = height(root.right);
return Math.max(leftHeight, rightHeight);
}Solution
Step 1: Check base case return value
Height of empty tree (null) should be 0 or consistent with counting edges. Returning -1 causes incorrect height calculation.Step 2: Check return statement
Method returns max of left and right heights but misses adding 1 for current node, so height is underestimated.Final Answer:
The base case should return 0, not -1. -> Option CQuick Check:
Base case must return 0 for correct height [OK]
- Returning -1 in base case
- Not adding 1 to max height
- Returning sum instead of max
Solution
Step 1: Find height recursively
Use a recursive method to find the height of the tree, which gives the maximum depth level.Step 2: Use level-order traversal
Perform a breadth-first traversal (level-order) and print nodes only at the level equal to the height found.Final Answer:
First find height recursively, then use a level-order traversal to print nodes at that height. -> Option AQuick Check:
Separate height calculation + level-order print = First find height recursively, then use a level-order traversal to print nodes at that height. [OK]
- Trying to print during height recursion
- Using in-order traversal for level nodes
- Printing root only ignoring height
Ready to prove it?
Pass the test and this pattern moves unknown
