Code link: https://leetcode.com/problems/check-completeness-of-a-binary-tree/
Constraint:
- In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Idea
A full node means a node that contains both left and right child. If we do a level order traversal for a complete binary tree, after we see the first non-full node, all the subsequent nodes must be leaf nodes (no left or right child).
BFS iterative solution:
class Solution {
public boolean isCompleteTree(TreeNode root) {
boolean hasNonFullNode = false;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur.left != null) {
if (hasNonFullNode) {
return false;
}
queue.offer(cur.left);
} else {
hasNonFullNode = true;
}
if (cur.right != null) {
if (hasNonFullNode) {
return false;
}
queue.offer(cur.right);
} else {
hasNonFullNode = true;
}
}
return true;
}
}
-
Time: O(n).
-
Space: O(n).
-
Reference: https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/