balanced-binary-tree.sh — zsh
binary-treedepth-first-searchrecursion

Given the root of a binary tree, return true if the tree is height-balanced, or false otherwise.

A binary tree is height-balanced when, for every node, the heights of its left and right subtrees differ by no more than 1.

Input / output

  • Input: root: TreeNode (JSON test fixture is a LeetCode-style level-order array using null for missing children, for example [3,9,20,null,null,15,7])
  • Output: boolean

Examples

  1. root = [3,9,20,null,null,15,7] returns true.
  2. root = [1,2,2,3,3,null,null,4,4] returns false.
  3. root = [] returns true because an empty tree is balanced.

Constraints

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

Follow-up Can you compute balance and height in the same postorder traversal so you never recompute subtree heights twice?

Examples
Example 1
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Example 3
Input: root = []
Output: true
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.