oneby7

Binary Trees Depth first: return a value up

348. Balanced Binary Tree

Easy

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

1354689

Input: root = [6, 3, 8, 1, 4, null, 9, null, null, 5]

Output: true

Explanation: 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 = []

Output: true

Explanation: The tree has no nodes, so no node can break the rule.

Example 3

017253-4

Input: root = [2, 7, 5, 1, null, null, 3, 0, null, null, -4]

Output: false

Explanation: 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.

root = [4, 2, 6, 1]

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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.