Explain balance checking.
Skip to solutionKEEP THE
mediumDSA
How do you check if a binary tree is balanced?
1.1k views
01
Understand the problem
treesbalanced
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Recurse computing subtree heights; if any node's left/right heights differ by more than 1, it's unbalanced. Return -1 as a sentinel to short-circuit, giving O(n) instead of O(n²) from recomputing heights.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Bottom-up balance check
Run Playgroundclass TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def is_balanced(root):
def height(node):
if not node:
return 0
lh = height(node.left)
if lh == -1: return -1
rh = height(node.right)
if rh == -1: return -1
if abs(lh - rh) > 1: return -1
return 1 + max(lh, rh)
return height(root) != -1
# --- demo ---
balanced = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))
skewed = TreeNode(1, TreeNode(2, TreeNode(3))) # 1->2->3 chain
print(is_balanced(balanced)) # True
print(is_balanced(skewed)) # False05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 37 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.