Practice · Trees · 1 of 12

Check a Binary Tree Is Balanced

You are given root, the root of a binary tree (or nothing, for an empty tree).

The tree is balanced if, at every node, the heights of the left and right subtrees differ by at most 1. A subtree's height is the number of nodes on its longest downward path, and an empty subtree has height 0. Return true if the tree is balanced and false otherwise. An empty tree is balanced.

Trees are written in level order, row by row from the top, with null where a node is missing: [4, 2, 7, null, 3] is 4 at the root, 2 and 7 below it, and 3 as the right child of 2.

Example 1

Input
root = [7, 3, 9, null, null, 8, 12]
Output
true
The root's subtrees have heights 1 and 2, which differ by only 1, and every other node is balanced too.

Example 2

Input
root = [5, 4, 6, 3, null, null, null, 2]
Output
false
At node 4, the left subtree (3 and 2) has height 2 and the right one is empty.

Constraints

  • The tree holds 0 to 1000 nodes.
  • Every value is between −10⁴ and 10⁴.