Skip to main content

Balanced Binary Tree

Return True if the tree is height-balanced Example: [3,9,20,null,null,15,7] => True

Balanced Binary Tree rewards clean traversal structure more than any clever shortcut. It's a great warm-up that builds traversal modeling without a ton of moving parts. Be clear about what a state is; that's the difference between BFS/DFS working or blowing up.

Examples

You write

is_balanced(root: Optional[TreeNode])

  1. Example 1

    Input
    [3,9,20,null,null,15,7]
    returns
    true
  2. Example 2

    Input
    [1,2,2,3,3,null,null,4,4]
    returns
    false

The pattern behind it

BFS & DFS

I reach for it when

  • You walk a grid, a graph or a tree and visit each cell once.
  • The word shortest appears and every step costs the same.

Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.

All 52 BFS & DFS problems

Trees

I reach for it when

  • Each node has children, and the answer depends on the subtrees.
  • The statement says depth, height, ancestor or path.

Say this before you type. Say what a call returns for an empty tree, and what it returns for a node.

All 22 Trees problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Balanced Binary Treeeasy