Skip to content
mlmentorship

Balanced Binary Tree

Return a certified subtree height or failure, propagate failure before combining, and distinguish local height from whole-tree balance.

Published · 10 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Balanced Binary Tree

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. The root of a finite binary tree, with left and right child references or None. Output. Return True exactly when every node's left and right subtree heights differ by at most one. Rules. Height counts nodes: an empty subtree has height zero and a leaf has height one. The condition must hold throughout the tree, not only at the root. Assume no cycles or shared children. Do not change any nodes; an empty tree is balanced. Example. A root with two leaf children returns True. A three-node chain containing only left children returns False; its root's subtree heights are two and zero.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

A postorder height function returns a nonnegative height for a balanced subtree and -1 as a failure sentinel that ancestors propagate immediately.

Problem trace

Compute child heights before certifying the parent

Input and goalCheck whether the child heights at every node differ by at most one.
Start bottom-up height evaluationCall height(1), then descend through 2 and 3 to leaf 4. No right sibling has been evaluated.
callStack[1,2,3,4]untouchedRightSubtree5 with children 6,7
node 1
stack start
node 2
stack
node 3
stack

Recognize it
Use a sentinel summary when a parent needs a normal child aggregate but any descendant failure should abort remaining work, as in balanced-height checks or invalid-subtree detection.
Keep true
height(node) returns the exact nonnegative subtree height if every node below is balanced; otherwise it returns -1. Thus ancestors can distinguish valid data from failure without a second traversal.
Reuse it
Fuse a subtree summary with validation by reserving an impossible summary value for failure, then check it before doing more recursion; this generalizes to BST validation and parse-tree error propagation.
Call height(1), then descend through 2 and 3 to leaf 4. No right sibling has been evaluated. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does the root return without visiting nodes 5, 6 and 7?
Full interview answer 10 min read

Determine whether every node in a binary tree has subtrees of nearly equal height.

Problem

Input. The root of a finite binary tree, with left and right child references or None.

Output. Return True exactly when every node’s left and right subtree heights differ by at most one.

Rules. Height counts nodes: an empty subtree has height zero and a leaf has height one. The condition must hold throughout the tree, not only at the root. Assume no cycles or shared children. Do not change any nodes; an empty tree is balanced.

Example. A root with two leaf children returns True. A three-node chain containing only left children returns False; its root’s subtree heights are two and zero.

Picture

Follow the left chain upward. Valid heights stop at node 2; the root then skips its right subtree.

NodeLeft resultRight resultReturned result
4001
3102
220-1: unbalanced
1-1Not called-1: propagate failure

Problem trace

An unbalanced child can end the check before further searching

Worked example: a failed child cannot be repaired by a balanced parentA child returns the unbalanced sentinel, not a usable height. Propagate that failure rather than averaging or comparing it as a valid depth.A failed child is not a usable heightleft returnFAILright return2gatepropagateFAILNo valid sibling height repairs FAIL.
Read it this way: A child returns the unbalanced sentinel, not a usable height. Propagate that failure rather than averaging or comparing it as a valid depth. Can an arbitrarily large valid height from the other child repair the failed child?
Reference drawing

Problem trace

An unbalanced child can end the check before further searching

Worked example: a failed child cannot be repaired by a balanced parentA child returns the unbalanced sentinel, not a usable height. Propagate that failure rather than averaging or comparing it as a valid depth.A failed child is not a usable heightleft returnFAILright return2gatepropagateFAILNo valid sibling height repairs FAIL.
Execution trace
Input and goalCheck whether the child heights at every node differ by at most one.
Start bottom-up height evaluationCall height(1), then descend through 2 and 3 to leaf 4. No right sibling has been evaluated.
callStack[1,2,3,4]untouchedRightSubtree5 with children 6,7
node 1
stack start
node 2
stack
node 3
stack

Recognize it
Use a sentinel summary when a parent needs a normal child aggregate but any descendant failure should abort remaining work, as in balanced-height checks or invalid-subtree detection.
Keep true
height(node) returns the exact nonnegative subtree height if every node below is balanced; otherwise it returns -1. Thus ancestors can distinguish valid data from failure without a second traversal.
Reuse it
Fuse a subtree summary with validation by reserving an impossible summary value for failure, then check it before doing more recursion; this generalizes to BST validation and parse-tree error propagation.
Call height(1), then descend through 2 and 3 to leaf 4. No right sibling has been evaluated. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does the root return without visiting nodes 5, 6 and 7?
Read it this way: A child returns the unbalanced sentinel, not a usable height. Propagate that failure rather than averaging or comparing it as a valid depth. Can an arbitrarily large valid height from the other child repair the failed child?

Root-only testing fails here. Its child heights are three and two, only one apart; node 2 still violates the condition.

Code

Use this node type for a local run.

from dataclasses import dataclass


@dataclass
class TreeNode:
   val: int
   left: "TreeNode | None" = None
   right: "TreeNode | None" = None
def is_balanced(root: TreeNode | None) -> bool:
   def height(node: TreeNode | None) -> int:
      if node is None:
         return 0

      left = height(node.left)
      if left < 0:
         return -1

      right = height(node.right)
      if right < 0 or abs(left - right) > 1:
         return -1
      return 1 + max(left, right)

   return height(root) >= 0

Extend the Returned Contract

A nonnegative return is the exact height. It also certifies balance everywhere in that subtree.

The value -1 means failure, not another height.

Every legitimate height is nonnegative, so this sentinel cannot collide with valid data.

Check left failure before calling right. Then check right failure and the local difference before returning a height.

Both certified children and an acceptable local difference are necessary. Ignoring a descendant’s failure loses the whole-tree guarantee.

Each visited node does constant work: worst-case time and call-stack space for height .

Recomputing heights separately at every node can take quadratic time along a chain. Deep trees can exceed Python’s recursion limit.

The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.

Recall: Why propagate failure before combining heights? A failed child has no certified height in this interface.

Keep Height Even on Failure

Choose this when: The caller needs the actual height of an unbalanced tree too.

Return height and validity separately. Visit both children even when one is unbalanced; otherwise the requested height could be wrong.

def height_and_balance(root):
   if root is None:
      return [0, True]
   left_height, left_ok = height_and_balance(root.left)
   right_height, right_ok = height_and_balance(root.right)
   return [
      1 + max(left_height, right_height),
      left_ok and right_ok and abs(left_height - right_height) <= 1,
   ]

A three-node one-sided chain returns [3, False]; an empty tree returns [0, True].

Unlike the sentinel version, this interface preserves the aggregate after validation fails. It visits all nodes in time and retains stack space.

Change the Allowed Difference

Choose this when: Every local height difference may be at most a supplied nonnegative tolerance.

def balanced_with_tolerance(root, tolerance):
   if tolerance < 0:
      raise ValueError("nonnegative tolerance required")

   def height(node):
      if node is None:
         return 0
      left = height(node.left)
      if left < 0:
         return -1
      right = height(node.right)
      if right < 0 or abs(left - right) > tolerance:
         return -1
      return 1 + max(left, right)

   return height(root) >= 0

The same three-node chain passes tolerance two and fails tolerance one. Zero requires equal child heights at every node. Negative tolerance raises ValueError, including for an empty tree.

Only the local threshold changes. Every descendant must still pass. Worst-case time remains and stack space .

Transfer

A failure sentinel is useful only while it cannot be mistaken for a valid summary. If callers need the summary after failure, return validity separately instead of discarding it.