222 count complete tree nodes

Best Answer

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
def (self, root):
"""
:type root: TreeNode
:rtype: int
"""
height = 0
temp = root

while temp != None:
height += 1
temp = temp.left
return self.count(root, height)

def count(self, root, maxHeight):
if root is None:
return 0
if root.left is None:
return 1
height = 0
temp = root.left
while temp != None:
height += 1
temp = temp.right
if height == (maxHeight - 1): # left tree is perfect at the lowest level
return pow(2, height) + self.count(root.right, maxHeight - 1)
else: # right tree must be perfect at one level shallower
return pow(2, height) + self.count(root.left, maxHeight - 1)

Time complexity: O(logn) * O(logn)
Space Complexity: O(1)

for each node
check the depth of left node of right most sub tree
if depth + current height == max height of tree
means left node is a full binary tree
add current node # and go to right sub tree
else
means left node is not a full binary tree
so right node is also not a full binary tree in max height
add current node # and go to left sub treeh