-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path222_CountCompleteTreeNodes.py
More file actions
46 lines (42 loc) · 1.21 KB
/
222_CountCompleteTreeNodes.py
File metadata and controls
46 lines (42 loc) · 1.21 KB
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
42
43
44
45
46
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer}
def countNodes(self, root):
if not root:
return 0
height = self.countLeftHeight(root)
node = root
level = 1
count = height
while True:
lh = self.countLeftHeight(node)
rh = self.countRightHeight(node)
if lh - rh == 1:
# look at the right halve tree
if rh == self.countLeftHeight(node.right):
count -= height / (2 ** level)
node = node.left
else:
node = node.right
level += 1
else:
# lh == rh
break
count += height * (height - 1) / 2
return count
def countLeftHeight(self, root):
height = 1
while root.left:
height += 1
return height
def countRightHeight(self, root):
height = 1
while root.right:
height += 1
return height