Tensorum
LeetCode 110 · DFS Basics

Balanced Binary Tree

LeetCode 110 · Easy · solution, intuition & step-by-step walkthrough

Height DFS that returns −1 on imbalance.

EasyTreeDepth-First SearchBinary Tree
66 msruntime · beats 6%
53.6 MBmemory · beats 100%
1approach
4accepted runs · last 25 Jun 2024

This is how I solved Balanced Binary Tree (LeetCode 110), an easy problem from the DFS Basics pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Compute heights bottom-up, and use −1 as a signal that a subtree is already unbalanced. That way each node is visited once and an imbalance short-circuits everything above it.

Approach

  1. 1

    Empty → height 0.

  2. 2

    Get the left height; −1 → propagate.

  3. 3

    Get the right height; −1 → propagate.

  4. 4

    Difference > 1 → −1; else 1 + max.

How I solved it

Height with sentinelPythonO(n) time · O(h) space
class Solution:
    def isBalanced(self, root):
        def dfs(node):
            if node is None:
                return 0
            lh = dfs(node.left)
            if lh == -1:
                return -1
            rh = dfs(node.right)
            if rh == -1:
                return -1
            if abs(lh - rh) > 1:
                return -1
            return 1 + max(lh, rh)
        return dfs(root) != -1
Loading the step-through…

Balanced Binary Tree — FAQ

What is the intuition behind Balanced Binary Tree?

Compute heights bottom-up, and use −1 as a signal that a subtree is already unbalanced. That way each node is visited once and an imbalance short-circuits everything above it.

How do you solve Balanced Binary Tree (LeetCode 110)?

1. Empty → height 0. 2. Get the left height; −1 → propagate. 3. Get the right height; −1 → propagate. 4. Difference > 1 → −1; else 1 + max.

What is the time and space complexity of Balanced Binary Tree?

Time: O(n). Space: O(h). (Accepted approach: Height with sentinel.)

What are common mistakes in Balanced Binary Tree?

Computing height separately at every node is O(n²).