AceYourInterviews
Checking sign-in…

83. Balanced Binary Tree

CorePostorder height certification at every subtree root

Check whether each node's left and right subtree heights differ by at most one. The requirement applies at every node in the tree.

A small height difference at the root is not sufficient if a lower subtree is unbalanced. Preserve the tree while inspecting it.

Example 1

Input

[3,9,20,null,null,15,7]

Output

true

Explanation: Every local height difference is zero or one.

Example 2

Input

[1,2,2,3,null,3,null,4,null,4]

Output

false

Explanation: Root sides have equal height, but lower nodes each have a two-level imbalance.

Constraints

  • 0 <= node count per tree <= 105
  • -231 <= node.value <= 231 - 1
  • Each input is a proper binary tree: no cycles or shared child nodes. Null trees are permitted.
Hints
Hint 1

A parent needs more than a boolean from each child.

Hint 2

Compute height and local validity together, once per node.

Hint 3

Use postorder; reject the first completed frame whose child heights differ by more than one.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Certify child heights bottom up

[3,9,20,null,null,15,7]
true