← Questions

Check whether a binary tree is a max-heap

0
MetaCodingLast asked Jul 2025

A coding interview question asked in Meta's AI-enabled coding round, last asked Jul 2025. It tests binary tree, heaps and bfs.

Decide whether a binary tree is a valid max-heap. Two things must hold: the tree is complete (every level is full except possibly the last, which is filled from the left with no gaps), and every node's value is at least as large as each of its children's.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • is_max_heap(root: TreeNode | None) -> bool — an empty tree and a single node are valid.
  • In examples the tree is written in level order, with None for a missing child.

Example

is_max_heap([9, 7, 8, 3, 6, 2, 1])  ->  True
is_max_heap([9, 7, 8, 3, 6])        ->  True    # last level filled from the left
is_max_heap([9, 7, 8, None, 6])     ->  False   # a gap before 6
is_max_heap([9, 7, 8, 3, 10])       ->  False   # 10 is larger than its parent 7

Constraints

  • 0 <= number of nodes <= 10^4; values fit in 32-bit integers; duplicates allowed.
  • Target O(n) time.

Clarifying questions

  • Max-heap or min-heap, and are equal parent and child values allowed?
  • Is an empty tree valid?
  • Do I get a node structure or an array?

What a strong answer covers

  • A BFS that enqueues both children, including missing ones; once a missing child is dequeued, any later real node breaks completeness.
  • Checking heap order against each present child during the same pass.
  • The alternative: number nodes like an array (root 1, children 2i and 2i + 1) and check the largest index equals the node count.
  • Why a plain DFS struggles: it sees parent-child order but not left-to-right gaps across a level, unless it carries the index.
  • Tests: empty, a single node, a right child without a left one, equal values.

Follow-ups

  • The heap is given as an array: check it in place.
  • Turn a complete binary tree into a max-heap (heapify) in O(n).
  • Check a binary search tree instead, and compare the two checks.

Where it's asked

  • Meta · AI-enabled coding · Last asked Jul 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

binary tree · heaps · bfs

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding