Skip to the code
cf.
+10 XP

#346 Balanced Layout Check

easy

A layout engine renders fastest when its split tree is height-balanced: at every node, the heights of the left and right subtrees differ by at most 1. The height of an empty subtree is 0.

Write isBalanced(root) that returns true if every node meets that rule and false otherwise. An empty tree is balanced.

Example 1

Input: root = [1,2,3,4,5]
Output: true

At the root, the heights are 2 and 1. Every other node is balanced too.

Example 2

Input: root = [1,2,null,3]
Output: false

The root's left subtree has height 2 and its right subtree height 0.

Constraints

  • 0 <= number of nodes <= 5000

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).