Skip to the solution
MediumDSA14 min read

How do you check if a binary tree is balanced?

1.1k views

The problem

Question presented to candidate: "You are given the root of a binary tree, a tree of Node objects with val, left and right. Write a Python function that returns true if the tree is height-balanced โ€” meaning that at every node, the heights of the left and right subtrees differ by at most one โ€” and false otherwise."

What a strong answer should cover:

  • The definition applies at every node, not just the root, and an empty tree is balanced.
  • The naive top-down approach (compute both heights at every node) and why it repeats work: O(n ยท h), so O(n log n) on a balanced tree.
  • The bottom-up post-order approach: return the height, or a sentinel such as -1 as soon as a subtree fails, so the whole check is O(n).
  • Space is the recursion stack, O(h): O(log n) when balanced, O(n) for a chain.
  • Python details: compare the sentinel with == -1 (height 0 is falsy), and the default recursion limit of 1000 for skewed trees.
  • Why balance matters: search trees stay O(log n) only while their height is small.

Clarifying questions expected:

  • Is "balanced" the height-gap-at-most-one definition, and is an empty tree balanced?
  • Can the tree be very deep (risk of stack overflow)?

Code / implementation expected: Yes โ€” check_height(node) returning an int, plus is_balanced(root), in Python 3.

  • trees
  • balanced

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBottom-up check with a -1 sentinel (7 trees)
PythonTop-down vs bottom-up: nodes touched

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 49 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you detect a cycle in a directed graph?

Continue