原题
https://leetcode.com/problems/check-completeness-of-a-binary-tree/
解法
BFS. 按层将节点(包括空节点)放入队列, 依次从左边取出节点, 如果已发现一个空节点, 并且空节点后面还有节点, 返回False.
Time: O(n), n为节点数
Space: O(n)
代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isCompleteTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# base case
if not root: return True
q = [root]
missing = False
while q:
size = len(q)
while size > 0:
node = q.pop(0)
size -= 1
if node is None:
missing = True
else:
# if there exists a node after a missing node
if missing:
return False
q.append(node.left)
q.append(node.right)
return True