Binary Trees Depth first: return a value up
348. Balanced Binary Tree
You are given root, the root node of a binary tree. Return true if the tree is height-balanced, and
false otherwise.
The height of a subtree is the number of nodes on the longest path from its top node down to a leaf. An empty subtree has height 0. A tree is height-balanced when, at every node, the heights of the left and right subtrees differ by at most 1. Every node must pass, not only the root. An empty tree is height-balanced.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [6, 3, 8, 1, 4, null, 9, null, null, 5]
trueExplanation: At 3, the left subtree has height 1 and the right subtree, 4 → 5, has height 2. At 8 the heights are 0 and 1, and at the root they are 3 and 2. Every node is off by at most 1.
Example 2
Input: root = []
trueExplanation: The tree has no nodes, so no node can break the rule.
Example 3
Input: root = [2, 7, 5, 1, null, null, 3, 0, null, null, -4]
falseExplanation: Both sides of the root have height 3, so the root is fine. But 7 has a left subtree of height 2 and no right subtree, a difference of 2. The same happens at 5.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
Clarifying questions
What you would ask an interviewer before writing any code.