mediumDSA

How do you check if a binary tree is balanced?

1.1k views
01

Understand the problem

Explain balance checking.

treesbalanced
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Bottom-up balance check
Run Playground
class 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))     # False
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.