Check Completeness of a Binary Tree
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
1to100nodes. 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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| Heap indices (DFS) | O(n) | O(h) |
| BFS until the first gap | O(n) | O(w) |
1Heap indices (DFS)
O(n)O(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.
- Count the nodes n.
- DFS with an index; if a node's index is >= n, return false.
- 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);
}
}class Solution:
def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
def count(node: Optional[TreeNode]) -> int:
if node is None:
return 0
return 1 + count(node.left) + count(node.right)
def check(node: Optional[TreeNode], idx: int, n: int) -> bool:
if node is None:
return True
if idx >= n:
return False
return check(node.left, 2 * idx + 1, n) and check(node.right, 2 * idx + 2, n)
return check(root, 0, count(root))class Solution {
public:
bool isCompleteTree(TreeNode* root) {
int n = count(root);
return check(root, 0, n);
}
private:
int count(TreeNode* node) {
if (node == nullptr) return 0;
return 1 + count(node->left) + count(node->right);
}
bool check(TreeNode* node, int idx, int n) {
if (node == nullptr) return true;
if (idx >= n) return false;
return check(node->left, 2 * idx + 1, n) && check(node->right, 2 * idx + 2, n);
}
};function isCompleteTree(root) {
const count = (node) => node === null ? 0 : 1 + count(node.left) + count(node.right);
const check = (node, idx, 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);
};
return check(root, 0, count(root));
}2BFS until the first gap
O(n)O(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.
- Put root in a queue; seenNull = false.
- Poll a node. If it is null, set seenNull = true.
- Otherwise, if seenNull is already true return false; else enqueue its left and right children (nulls included).
- 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;
}
}class Solution:
def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
q = deque([root])
seen_null = False
while q:
node = q.popleft()
if node is None:
seen_null = True
else:
if seen_null:
return False
q.append(node.left)
q.append(node.right)
return Trueclass Solution {
public:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
bool seenNull = false;
while (!q.empty()) {
TreeNode* node = q.front(); q.pop();
if (node == nullptr) {
seenNull = true;
} else {
if (seenNull) return false;
q.push(node->left);
q.push(node->right);
}
}
return true;
}
};function isCompleteTree(root) {
const q = [root];
let head = 0;
let seenNull = false;
while (head < q.length) {
const node = q[head++];
if (node === null) {
seenNull = true;
} else {
if (seenNull) return false;
q.push(node.left);
q.push(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).