Balanced Binary Tree

Recursion returns height — propagate a -1 sentinel up if any subtree is unbalanced.

Easy
Time O(n) Space O(h)
LeetCode
3 min read
tree dfs recursion

Problem#

Return true iff a binary tree is height-balanced — for every node the heights of its two subtrees differ by at most 1.

Examples#

  • [3,9,20,null,null,15,7]true.
  • [1,2,2,3,3,null,null,4,4]false.

Constraints#

  • 0 <= nodes <= 5000.

Approach#

DFS returning height. If either subtree returns -1 (unbalanced) or their heights differ by more than 1, return -1. Otherwise return 1 + max(left, right).

Solution#

Balanced Binary Tree
struct TreeNode { int val; TreeNode* left; TreeNode* right; };
class Solution {
int height(TreeNode* n) {
if (!n) return 0;
int l = height(n->left); if (l < 0) return -1;
int r = height(n->right); if (r < 0) return -1;
if (abs(l - r) > 1) return -1;
return 1 + max(l, r);
}
public:
bool isBalanced(TreeNode* root) {
return height(root) >= 0;
}
};

Editorial#

The single-pass technique avoids the naive O(n^2) (recompute heights at every node). The -1 sentinel doubles as both “this is unbalanced” and “propagate the failure upward” — saves a separate boolean.

Complexity#

  • Time: O(n).
  • Space: O(h) recursion.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.