Check if a binary tree is height-balanced
A post-order height check that stops early the moment any subtree is found unbalanced.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
A tree is height-balanced when, at every node, the heights of its left and right subtrees differ by at most 1. Computing height bottom-up already visits every node once, so piggyback the balance check onto it: have each call return -1 the instant it or a subtree below it is unbalanced, so no later work wastes time on a tree that has already failed.
Code
public static int CheckHeight(TreeNode node) {
if (node == null) return 0;
int left = CheckHeight(node.left);
if (left == -1) return -1;
int right = CheckHeight(node.right);
if (right == -1) return -1;
if (Math.Abs(left - right) > 1) return -1;
return 1 + Math.Max(left, right);
}static int checkHeight(TreeNode node) {
if (node == null) return 0;
int left = checkHeight(node.left);
if (left == -1) return -1;
int right = checkHeight(node.right);
if (right == -1) return -1;
if (Math.abs(left - right) > 1) return -1;
return 1 + Math.max(left, right);
}int checkHeight(TreeNode* node) {
if (!node) return 0;
int left = checkHeight(node->left);
if (left == -1) return -1;
int right = checkHeight(node->right);
if (right == -1) return -1;
if (abs(left - right) > 1) return -1;
return 1 + max(left, right);
}def check_height(node: TreeNode | None) -> int:
if node is None: return 0
left = check_height(node.left)
if left == -1: return -1
right = check_height(node.right)
if right == -1: return -1
if abs(left - right) > 1: return -1
return 1 + max(left, right)Tips
- A naive version recomputes height for every node from scratch, costing O(n²) on a skewed tree. The -1 sentinel keeps it O(n).
- Try a long chain of inserts (sorted keys) to see an unbalanced tree.
In the .NET library
This -1-sentinel trick (fold a yes/no check into a value-returning computation) shows up again whenever a bottom-up pass needs to bail out early, such as validating a BST.