Problem 411010 · medium · Level 04 Non-Linear Data Structures

Height-Balanced Check

binary trees · recursion · post-order aggregation

A binary tree is height-balanced if, for every node, the heights of its left and right subtrees differ by at most 1. Given the root, return True if the tree is height-balanced. An empty tree is balanced.

Examples

    8
   / \
  4  13
     / \
    12  6

Input:  root = build_tree([8, 4, 13, None, None, 12, 6])
Output: True
       6
      / \
     2   9
    / \
   1   4
  / \
 0   3

Input:  root = build_tree([6, 2, 9, 1, 4, None, None, 0, 3])
Output: False
Explanation: at the root, the left subtree has height 3 and the right has height 1.

Constraints

  • 0 <= number of nodes <= 2000
  • Target complexity: O(n) time.

Goals

  • Compute subtree heights bottom-up
  • Propagate a failure signal without recomputing heights
  • Avoid the O(n^2) naive approach
Starting Python…