Given the root
of a binary tree, determine if it is a complete binary tree. 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 2<sup>h</sup>
nodes inclusive at the last level h
.
Example 1: Consider the following binary tree:
1
/ \
2 3
/ \ /
4 5 6
Input: root = [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (i.e., levels with node-values {1}
and {2, 3}
), and all nodes in the last level {4, 5, 6}
are as far left as possible.
Example 2: Consider the following binary tree:
1
/ \
2 3
/ \ \
4 5 7
Input: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
Constraints:
[1, 100]
.1 <= Node.val <= 1000
A brute-force approach involves performing a level-order traversal of the binary tree and keeping track of the number of nodes at each level. While traversing, we check if each level is full (i.e., has the maximum possible number of nodes for that level) until we encounter a level that is not full. We will know the tree is not complete binary tree if we find a node after the first gap.
A more efficient approach is to use a level-order traversal and look for the first null
node. If we encounter a null
node, then all subsequent nodes in the level order traversal must be null
. If we find a non-null node after encountering the first null node, it's not a complete binary tree.
null
node.null
node, set the flag to true
.null
node after the flag is true
, return false
.null
node after a null
node, return true
.from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isCompleteTree(root: TreeNode) -> bool:
if not root:
return True
queue = deque([root])
seen_null = False
while queue:
node = queue.popleft()
if node is None:
seen_null = True
else:
if seen_null:
return False
queue.append(node.left)
queue.append(node.right)
return True
Consider the tree: [1,2,3,4,5,null,7]
The level-order traversal is [1, 2, 3, 4, 5, null, 7]
1
is added to the queue.1
is popped. 2
and 3
are added.2
is popped. 4
and 5
are added.3
is popped. null
and 7
are added.4
is popped. null
and null
are added.5
is popped. null
and null
are added.null
is popped. seen_null
is set to True
.7
is popped. Since seen_null
is True
, we return False
.