Check if Binary Tree is Balanced in DSA Java - Time & Space Complexity
We want to understand how long it takes to check if a binary tree is balanced.
Specifically, how the time grows as the tree gets bigger.
Analyze the time complexity of the following code snippet.
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
int leftHeight = height(root.left);
int rightHeight = height(root.right);
if (Math.abs(leftHeight - rightHeight) > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
private int height(TreeNode node) {
if (node == null) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
This code checks if a binary tree is balanced by comparing heights of left and right subtrees recursively.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls to
height()for each node. - How many times: For each node,
height()is called multiple times due to repeated subtree height calculations.
As the tree size grows, the height function is called many times for the same nodes, causing repeated work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 calls (due to repeated height calculations) |
| 100 | About 10,000 calls |
| 1000 | About 1,000,000 calls |
Pattern observation: The number of operations grows roughly with the square of the number of nodes.
Time Complexity: O(n²)
This means the time to check balance grows quickly as the tree gets bigger, roughly proportional to the square of the number of nodes.
[X] Wrong: "The code runs in linear time because it visits each node once."
[OK] Correct: The height function is called repeatedly for the same nodes, causing many extra visits and increasing total work.
Understanding this helps you explain why some recursive solutions can be inefficient and how to improve them.
"What if we modified the code to calculate height and balance in the same recursion? How would the time complexity change?"
Practice
Solution
Step 1: Understand balance condition
A balanced binary tree means the height difference between left and right subtrees of every node is at most 1.Step 2: Compare other options
Options A, B, and C describe different tree properties but not the balance condition.Final Answer:
The height difference between left and right subtrees of every node is at most 1 -> Option AQuick Check:
Balance means height difference ≤ 1 [OK]
- Confusing balanced with complete tree
- Thinking balance means equal number of nodes
- Assuming all nodes must have two children
Solution
Step 1: Check Java method syntax
Correct Java method signature includes access modifier, return type, method name, and parameters: public boolean isBalanced(TreeNode root)Step 2: Identify incorrect syntax
Options A, C, and D have invalid order or keywords not used in Java method declarations.Final Answer:
public boolean isBalanced(TreeNode root) -> Option BQuick Check:
Java method syntax: access returnType name(params) [OK]
- Mixing return type and void
- Wrong keyword order
- Missing access modifier
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}
public class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
int leftHeight = height(root.left);
int rightHeight = height(root.right);
if (Math.abs(leftHeight - rightHeight) > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
private int height(TreeNode node) {
if (node == null) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.left.left = new TreeNode(5);
Solution sol = new Solution();
System.out.println(sol.isBalanced(root));
}
}Solution
Step 1: Calculate subtree heights
Left subtree of root has height 3 (nodes 2 -> 4 -> 5), right subtree has height 1 (node 3). Difference is 2 > 1.Step 2: Check balance condition
Since height difference > 1 at root, isBalanced returns false.Final Answer:
false -> Option AQuick Check:
Height difference > 1 means unbalanced = false [OK]
- Ignoring height difference > 1
- Assuming tree is balanced by default
- Confusing height with node count
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
int leftHeight = height(root.left);
int rightHeight = height(root.right);
if (Math.abs(leftHeight - rightHeight) > 1) return false;
return isBalanced(root.left) || isBalanced(root.right);
}
private int height(TreeNode node) {
if (node == null) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}Solution
Step 1: Analyze recursive calls
The code uses || (OR) to combine left and right subtree balance checks, which returns true if either subtree is balanced.Step 2: Correct logic for balance
Both left and right subtrees must be balanced, so && (AND) should be used instead of ||.Final Answer:
Using || instead of && in recursive call -> Option CQuick Check:
Balance requires both subtrees balanced: use && [OK]
- Using || instead of &&
- Forgetting base case
- Miscomputing height
Solution
Step 1: Identify inefficiency in naive approach
Naive method calculates height repeatedly for subtrees, causing extra work.Step 2: Use combined recursive function
Return height if subtree is balanced, else return -1 to indicate imbalance, avoiding repeated height calls.Final Answer:
Calculate height and balance in one recursive function returning a special value -> Option DQuick Check:
Combine height and balance check to optimize [OK]
- Recalculating height multiple times
- Using level order traversal which doesn't help balance check
- Checking balance only at root
Ready to prove it?
Pass the test and this pattern moves unknown
