-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_completeness_of_a_binary_tree.py
41 lines (32 loc) · 1.18 KB
/
check_completeness_of_a_binary_tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'''
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 2h nodes inclusive at the last level h.
'''
def isCompleteTree(self, root: TreeNode) -> bool:
end = False
queue = collections.deque([root])
while queue:
node = queue.popleft()
if not node:
end = True
else:
if end:
return False
else:
queue.append(node.left)
queue.append(node.right)
return True
------------------------------------
class Solution:
def isCompleteTree(self, root: TreeNode) -> bool:
have_null = False
Q = [root]
while Q:
cur_node = Q.pop(0)
if not cur_node:
have_null = True
continue
if have_null: return False
Q.append(cur_node.left)
Q.append(cur_node.right)
return True