Balanced Binary Tree — LeetCode 110 Python Solution

EasyTreeDepth-First SearchBinary Tree
Problem
#110
Reading time
3 min

The problem

Given a binary tree, determine if it is height-balanced.

Example

Input
root = [3,9,20,null,null,15,7]
Output
true

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        def height(root):
            if root is None:
                return 0
            l, r = height(root.left), height(root.right)
            if l == -1 or r == -1 or abs(l - r) > 1:
                return -1
            return 1 + max(l, r)

        return height(root) >= 0

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 110. Balanced Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and Grind 75.

Frequently asked questions

How hard is LeetCode 110. Balanced Binary Tree?
LeetCode 110. Balanced Binary Tree is rated Easy on LeetCode.
What is the time complexity of LeetCode 110. Balanced Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 110. Balanced Binary Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 110. Balanced Binary Tree cover?
LeetCode 110. Balanced Binary Tree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview