Balanced Binary Tree

EasyTreestree dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree, return true if the tree is height-balanced and false otherwise. A tree is height-balanced when, at **every** node, the heights of the left and right subtrees differ by at most one. The height of an empty subtree is 0. An empty tree is balanced. Checking only the root is not enough: a tree whose two root subtrees have equal height can still be unbalanced deeper down. Target O(n) time.

Examples

Input: root = [3,9,20,null,null,15,7]
Output: true
Every node has subtrees whose heights differ by at most 1.
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
At the root, the left subtree has height 3 and the right has height 1.
Input: root = []
Output: true
The empty tree is balanced.

Constraints

  • 0 <= number of nodes <= 5000
  • -10^4 <= Node.val <= 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More tree dp problems