Check Completeness of a Binary Tree

Medium Trees & BST Traversals

Check Completeness of a Binary Tree is a medium trees & bst problem solved with the traversals pattern. The best approach, bfs until the first gap, runs in O(n) time and O(w) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from heap indices (dfs) up.

Problem

A binary tree is complete when every level is completely filled except possibly the deepest one, and the nodes on that deepest level sit as far to the left as they can, with no holes between them. Given the root of a binary tree, return true if it is complete and false otherwise.

Examples

Example 1

Input
root = [8, 3, 5, 1, 9, 2]
Output
true
Why
The first two levels are full and the last level holds 1, 9, 2 packed against the left.

Example 2

Input
root = [8, 3, 5, null, 9]
Output
false
Why
Node 3 has no left child but does have a right child, so there is a gap before 9.

Example 3

Input
root = [6, 4, 7, 2, null, 1]
Output
false
Why
The last level has a hole between 2 and 1.

Constraints

  • The tree has 1 to 100 nodes.
  • 1 <= Node.val <= 1000

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 55 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Heap indices (DFS)O(n)O(h)
BFS until the first gapO(n)O(w)

1Heap indices (DFS)

TimeO(n)
SpaceO(h)

Give each node its heap position (root 0, children 2i+1 and 2i+2). The tree is complete exactly when every position is smaller than the node count n.

  1. Count the nodes n.
  2. DFS with an index; if a node's index is >= n, return false.
  3. Otherwise recurse into both children with 2i+1 and 2i+2.
class Solution {
    public boolean isCompleteTree(TreeNode root) {
        int n = count(root);
        return check(root, 0, n);
    }

    private int count(TreeNode node) {
        if (node == null) return 0;
        return 1 + count(node.left) + count(node.right);
    }

    private boolean check(TreeNode node, int idx, int n) {
        if (node == null) return true;
        if (idx >= n) return false;
        return check(node.left, 2 * idx + 1, n) && check(node.right, 2 * idx + 2, n);
    }
}

2BFS until the first gap

TimeO(n)
SpaceO(w)

Walk the tree level by level, enqueuing children even when they are null. Once a null has been seen, any later real node means a gap.

  1. Put root in a queue; seenNull = false.
  2. Poll a node. If it is null, set seenNull = true.
  3. Otherwise, if seenNull is already true return false; else enqueue its left and right children (nulls included).
  4. If the queue empties, return true.
class Solution {
    public boolean isCompleteTree(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        boolean seenNull = false;
        while (!q.isEmpty()) {
            TreeNode node = q.poll();
            if (node == null) {
                seenNull = true;
            } else {
                if (seenNull) return false;
                q.add(node.left);
                q.add(node.right);
            }
        }
        return true;
    }
}

Edge cases to test

  • Single node (complete)
  • Only a left child at the bottom (complete)
  • Only a right child somewhere (not complete)
  • A missing node in a level above the last one
  • Perfect tree (complete)

Hints

Hint 1

Number the nodes like a heap: root is 0, the children of i are 2i + 1 and 2i + 2. When is a tree with n nodes complete?

Hint 2

In a level-order walk that also enqueues null children, a complete tree never shows a real node after the first null.

FAQ

What is the best time complexity for Check Completeness of a Binary Tree?

BFS until the first gap runs in O(n) time and O(w) extra space.

Which pattern does Check Completeness of a Binary Tree use?

It is a trees & bst problem that uses the traversals pattern. Other problems with the same pattern: Binary Tree Level Order Traversal, Binary Tree Zigzag Level Order Traversal, Binary Tree Level Order Traversal II.

Is there a brute force solution for Check Completeness of a Binary Tree?

Yes. Heap indices (DFS) takes O(n) time and O(h) space. Give each node its heap position (root 0, children 2i+1 and 2i+2).

Which edge cases should I test for Check Completeness of a Binary Tree?

Single node (complete); Only a left child at the bottom (complete); Only a right child somewhere (not complete); A missing node in a level above the last one; Perfect tree (complete).