CodeArchon

easyTreesGoogleAmazonBloomberg

Silo Balance Monitor

A silo inventory router checks whether storage structures have evenly balanced bins to distribute physical load safely.

Given a binary tree, determine if it is height-balanced (heights of left and right of every node differ by at most 1).

Choose approach

3
curr
9
20
15
7
1/11
Narrationstep 1 of 11

Validate node 3. Check left & right subtrees balance status.

1def isBalanced(root: Optional[TreeNode]) -> bool:
2 def check(node: Optional[TreeNode]) -> int:
3 if not node:
4 return 0
5 l = check(node.left)
6 if l == -1: return -1
7 r = check(node.right)
8 if r == -1: return -1
9 if abs(l - r) > 1: return -1
10 return 1 + max(l, r)
11 return check(root) != -1
Variables
curr=3

How to think about it

  1. Height of empty tree is 0.
  2. Evaluate each node's left and right heights recursively.
  3. Bubble up -1 on structural imbalance, which prevents wasteful overhead on further branches.

Edge cases to catch in interview

  • Empty tree -> balanced.
  • Deeply left-skewed or right-skewed tree -> false.

Examples

Example 1true
{"arr":[3,9,20,null,null,15,7]}
Example 2false
{"arr":[1,2,2,3,3,null,null,4,4]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed