Algo-Sim › Binary Trees & BST

Balanced Binary Tree

Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Every node’s two subtree heights must differ by at most 1. Return heights bottom-up, with −1 meaning “already unbalanced”, for one O(n) pass.

Problem

Given the root of a binary tree, return true if it is height-balanced: for every node, the heights of its left and right subtrees differ by at most 1.

Constraints

Edge cases to test

Follow-up questions

Why return −1 for unbalanced?
It lets one O(n) pass report height and failure together; computing heights separately at every node is O(n²).
How do you make a tree balanced?
Inorder to a sorted list, then rebuild from the middle out (LC 1382): O(n).

Solution

Java

public boolean isBalanced(TreeNode root) {
    return height(root) != -1;
}

// Height of the subtree, or -1 if any part of it is unbalanced.
private int height(TreeNode node) {
    if (node == null) return 0;
    int left = height(node.left);
    if (left == -1) return -1;
    int right = height(node.right);
    if (right == -1) return -1;
    if (Math.abs(left - right) > 1) return -1;
    return 1 + Math.max(left, right);
}

Python

def is_balanced(root):
    # Height of the subtree, or -1 if any part of it is unbalanced.
    def height(node):
        if not node:
            return 0
        left = height(node.left)
        if left == -1:
            return -1
        right = height(node.right)
        if right == -1:
            return -1
        if abs(left - right) > 1:
            return -1
        return 1 + max(left, right)

    return height(root) != -1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isBalanced(TreeNode *root) {
        return height(root) != -1;
    }

    // Height of the subtree, or -1 if any part of it is unbalanced.
    int height(TreeNode *node) {
        if (node == nullptr)
            return 0;
        int left = height(node->left);
        if (left == -1)
            return -1;
        int right = height(node->right);
        if (right == -1)
            return -1;
        if (abs(left - right) > 1)
            return -1;
        return 1 + std::max(left, right);
    }
};

More Binary Trees & BST problems