Skip to content

Commit 6975d1b

Browse files
authored
Create Check Completeness of a Binary Tree.py
1 parent 95b6f8e commit 6975d1b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
'''
2+
Given a binary tree, determine if it is a complete binary tree.
3+
4+
Definition of a complete binary tree from Wikipedia:
5+
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.
6+
7+
8+
9+
Example 1:
10+
11+
12+
13+
Input: [1,2,3,4,5,6]
14+
Output: true
15+
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
16+
Example 2:
17+
18+
19+
20+
Input: [1,2,3,4,5,null,7]
21+
Output: false
22+
Explanation: The node with value 7 isn't as far left as possible.
23+
24+
Note:
25+
26+
The tree will have between 1 and 100 nodes.
27+
'''
28+
29+
# Definition for a binary tree node.
30+
# class TreeNode(object):
31+
# def __init__(self, x):
32+
# self.val = x
33+
# self.left = None
34+
# self.right = None
35+
36+
class Solution(object):
37+
def isCompleteTree(self, root):
38+
"""
39+
:type root: TreeNode
40+
:rtype: bool
41+
"""
42+
vec = [root]
43+
idx = 0
44+
while vec[idx]:
45+
vec.append(vec[idx].left)
46+
vec.append(vec[idx].right)
47+
idx += 1
48+
for i in xrange(idx+1, len(vec)):
49+
if vec[i]:
50+
return False
51+
return True

0 commit comments

Comments
 (0)