Check if Binary Tree is Balanced in DSA C# - 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 bool IsBalanced(TreeNode root) {
return CheckHeight(root) != -1;
}
private int CheckHeight(TreeNode node) {
if (node == null) return 0;
int leftHeight = CheckHeight(node.left);
if (leftHeight == -1) return -1;
int rightHeight = CheckHeight(node.right);
if (rightHeight == -1) return -1;
if (Math.Abs(leftHeight - rightHeight) > 1) return -1;
return Math.Max(leftHeight, rightHeight) + 1;
}
This code checks if a binary tree is balanced by measuring heights and verifying the difference is not more than one at any node.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Each node is visited exactly one time.
As the number of nodes increases, the function visits each node once to check heights.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The operations grow linearly with the number of nodes.
Time Complexity: O(n)
This means the time to check balance grows directly with the number of nodes in the tree.
[X] Wrong: "The function checks each node multiple times, so it is O(n²)."
[OK] Correct: The code uses a single pass recursion that returns height or failure early, so each node is visited once.
Understanding this time complexity helps you explain efficient tree checks clearly and confidently.
"What if the code separately calculated height for left and right subtrees without early failure? 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 B, C, and D describe different properties not related to balance.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 or full tree
- Thinking balance means equal number of nodes
- Assuming sorted order means balanced
Solution
Step 1: Identify correct return type and parameters
The function should return a boolean indicating if the tree is balanced and take the root node as input.Step 2: Check method signature correctness
public bool IsBalanced(TreeNode root) matches this: public bool IsBalanced(TreeNode root). Others have wrong return types or parameter types.Final Answer:
public bool IsBalanced(TreeNode root) -> Option AQuick Check:
Return bool, input TreeNode root [OK]
- Using int return type instead of bool
- Passing wrong parameter type like int
- Using void return type for a check function
class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int v) { val = v; }
}
// Tree:
// 1
// / \
// 2 3
// /
// 4
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
bool result = IsBalanced(root);
Console.WriteLine(result);
bool IsBalanced(TreeNode node) {
if (node == null) return true;
int leftHeight = Height(node.left);
int rightHeight = Height(node.right);
if (Math.Abs(leftHeight - rightHeight) > 1) return false;
return IsBalanced(node.left) && IsBalanced(node.right);
}
int Height(TreeNode node) {
if (node == null) return 0;
return 1 + Math.Max(Height(node.left), Height(node.right));
}Solution
Step 1: Calculate heights of subtrees
Node 2 has left subtree height 1 (node 4) and right subtree height 0, difference is 1 (allowed). Node 1 has left height 2 and right height 1, difference is 1 (allowed).Step 2: Check balance recursively
Node 4 and 3 are leaves (balanced). However, node 2's left subtree is height 1 and right is 0, difference 1 (balanced). So all nodes satisfy balance condition.Final Answer:
true -> Option DQuick Check:
Height difference ⤠1 at all nodes = true [OK]
- Miscounting subtree heights
- Not checking all nodes recursively
- Assuming difference > 0 means unbalanced
bool IsBalanced(TreeNode node) {
if (node == null) return true;
int leftHeight = Height(node.left);
int rightHeight = Height(node.right);
if (Math.Abs(leftHeight - rightHeight) > 1) return false;
return IsBalanced(node.left) || IsBalanced(node.right);
}
int Height(TreeNode node) {
if (node == null) return 0;
return 1 + Math.Max(Height(node.left), Height(node.right));
}Solution
Step 1: Analyze recursive condition
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 check
Both left and right subtrees must be balanced, so && (AND) should be used instead of ||.Final Answer:
Using || instead of && in recursive calls -> Option BQuick Check:
Balance requires both subtrees balanced, use && [OK]
- Using || instead of && in recursive checks
- Ignoring base case for null nodes
- Incorrect height calculation
Solution
Step 1: Understand repeated height calculation problem
Calculating height separately for each node causes repeated work, increasing time complexity.Step 2: Use combined recursive approach
Returning both height and balance status in one recursive call avoids repeated height calculations and improves efficiency.Final Answer:
Calculate height and balance in one recursive function returning a tuple -> Option CQuick Check:
Combine height and balance in one recursion for efficiency [OK]
- Separating height and balance checks causing repeated work
- Using BFS which doesn't directly check balance
- Using global dictionary unnecessarily complicates code
Ready to prove it?
Pass the test and this pattern moves unknown
