Check if Binary Tree is Balanced in DSA C++ - Time & Space Complexity
We want to know 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.
int height(TreeNode* root) {
if (!root) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + std::max(leftHeight, rightHeight);
}
bool isBalanced(TreeNode* root) {
if (!root) return true;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
if (abs(leftHeight - rightHeight) > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
This code checks if a binary tree is balanced by comparing heights of subtrees recursively.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
heightfunction is called repeatedly for each node. - How many times: For each node,
heightis called again on its children, causing repeated calculations.
As the tree size grows, the number of height calculations grows quickly because each node's height is recalculated many times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 calls |
| 100 | About 10,000 calls |
| 1000 | About 1,000,000 calls |
Pattern observation: The operations grow roughly with the square of the number of nodes.
Time Complexity: O(n²)
This means the time to check balance grows very fast as the tree gets bigger, roughly like the number of nodes squared.
[X] Wrong: "The height function is called only once per node, so the time is O(n)."
[OK] Correct: Actually, height is called many times for the same nodes during recursion, causing repeated work and increasing time.
Understanding this helps you explain why naive recursion can be slow and how to improve it, a key skill in interviews.
"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 B, C, and D describe other 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 BQuick 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: Identify correct parameter type
The function should accept a pointer to the root node (TreeNode* root) to access the tree.Step 2: Identify correct return type
It should return bool to indicate if the tree is balanced or not.Final Answer:
bool isBalanced(TreeNode* root); -> Option AQuick Check:
Pointer parameter + bool return = correct signature [OK]
- Passing node by value instead of pointer
- Using int or void as return type
- Missing pointer symbol * in parameter
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
int height(TreeNode* root) {
if (!root) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
bool isBalanced(TreeNode* root) {
if (!root) return true;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
if (abs(leftHeight - rightHeight) > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
int main() {
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);
std::cout << (isBalanced(root) ? "Balanced" : "Not Balanced") << std::endl;
return 0;
}Solution
Step 1: Calculate heights of subtrees
Left subtree has height 3 (nodes 2->4->5), right subtree height is 1 (node 3).Step 2: Check balance condition
Height difference at root is 3 - 1 = 2, which is greater than 1, so tree is not balanced.Final Answer:
Not Balanced -> Option AQuick Check:
Height difference > 1 means Not Balanced [OK]
- Ignoring height difference at root
- Assuming tree is balanced if only some nodes are balanced
- Confusing height with number of nodes
int height(TreeNode* root) {
if (!root) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
bool isBalanced(TreeNode* root) {
if (!root) return true;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
if (abs(leftHeight - rightHeight) > 1) return false;
isBalanced(root->left);
isBalanced(root->right);
return true;
}Solution
Step 1: Analyze isBalanced recursive calls
Recursive calls to isBalanced(root->left) and isBalanced(root->right) are made but their results are ignored.Step 2: Fix missing return statements
Must return the logical AND of these calls to correctly check balance in subtrees.Final Answer:
Missing return statements for recursive calls in isBalanced -> Option DQuick Check:
Recursive calls must return and combine results [OK]
- Ignoring return values of recursive calls
- Returning true too early
- Incorrect base case handling
Solution
Step 1: Understand repeated height calculation problem
Calculating height separately for each node causes repeated work and increases time complexity.Step 2: Use combined helper function
A helper function can return both height and balance status together, allowing one traversal to check balance efficiently.Final Answer:
Use a helper function that returns both height and balance status in one traversal -> Option CQuick Check:
Combine height and balance check in one pass [OK]
- Calculating height multiple times causing O(n²) time
- Checking balance only at root misses subtree imbalance
- Using BFS does not directly help balance check
Ready to prove it?
Pass the test and this pattern moves unknown
