Problem 150
Balanced Binary Tree
Easy · 10 pts · Tree, Depth-First Search, Binary Tree
Problem
A binary tree is height-balanced if, at every node, the heights of its left and right subtrees differ by at most 1. Decide whether the given tree is balanced. Checking only the root is not enough; every node must satisfy the rule. A single recursive pass can compute each subtree's height and report imbalance at the same time, for example by returning -1 for an unbalanced subtree.
Input
First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses).
Output
Print YES or NO.
Constraints
1 <= number of nodes <= 5000; -10000 <= value <= 10000
Example input
7 3 9 20 null null 15 7
Example output
YES
Explanation
At the root 3, the left subtree (just 9) has height 1 and the right subtree (20 with children 15 and 7) has height 2. They differ by 1, and every other node is also balanced, so the answer is YES.