Skip to content
BytePatterns

Height-Balanced Tree Check

EasyTrees & BST#post-order#early-exit~15m

Problem

A search index keeps its keys in a binary tree and rebuilds it whenever it gets lopsided. A tree is height-balanced when, at every node, the heights of the left and right subtrees differ by at most 1. Given the root of a binary tree, return True if it is height-balanced. The tree has up to 5,000 nodes, so computing the height again from every node is wasteful.

Examples

Input:  tree = 3, left 9, right 20 (children 15 and 7)
Output: True
Input:  tree = 1, left 2 (left child 3 with children 4 and 4, right child 3), right 2
Output: False
Why:    at the root the left side is 3 levels deep and the right side only 1
Input:  tree = empty
Output: True
Why:    edge case, an empty tree has nothing out of balance

Hints

0 / 3

Stuck on the idea rather than the code? Tree Depth and Balance covers it.