Imagine you are designing a system that needs to keep data balanced for efficient retrieval, like a balanced family tree where no branch is too deep compared to others.
Given a binary tree, determine if it is height-balanced. A height-balanced binary tree is defined as a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Input: The root node of a binary tree.
Output: Return true if the tree is height-balanced, otherwise false.
1 ≤ n ≤ 10^5 (number of nodes)Node values can be any integerTree can be skewed or complete
Edge cases: Empty tree → true (an empty tree is balanced)Single node tree → true (only one node, balanced)Completely skewed tree (all nodes only on one side) → false
def isBalanced(root: Optional[TreeNode]) -> bool:public boolean isBalanced(TreeNode root)bool isBalanced(TreeNode* root)function isBalanced(root)
def isBalanced(root):
# Write your solution here
pass
class Solution {
public boolean isBalanced(TreeNode root) {
// Write your solution here
return false;
}
}
#include <vector>
using namespace std;
bool isBalanced(TreeNode* root) {
// Write your solution here
return false;
}
function isBalanced(root) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: trueFailing to detect imbalance in skewed or deep subtree cases due to missing or incorrect height difference checks.✅ Add condition to return false immediately if abs(left_height - right_height) > 1 at any node.
Wrong: falseIncorrectly returning false for empty or single-node trees by not handling base cases.✅ Return true immediately if root is null or if node has no children.
Wrong: trueNot using early exit, causing incorrect results when imbalance is detected deep in the tree.✅ Implement early exit by returning a sentinel value (e.g., -1) to indicate imbalance and propagate it up.
Wrong: TLEUsing brute force approach that recomputes height for each node causing O(n^2) complexity.✅ Use a single postorder traversal that returns height and balance status simultaneously to achieve O(n).