-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountCompleteTreeNodes.py
More file actions
49 lines (41 loc) · 1.49 KB
/
Copy pathcountCompleteTreeNodes.py
File metadata and controls
49 lines (41 loc) · 1.49 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
47
48
49
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# count nodes in complete binary tree in better than O(n)
# O(log^2 n) solution
def countNodes(self, root: TreeNode | None) -> int:
if not root: return 0
# calculate the height
height = 0
curr = root
while curr:
height += 1
curr = curr.left
# maximum possible nodes at the last level
max_nodes_last_level = (1 << (height - 1))
def exists(root: TreeNode, index: int, height: int) -> bool:
left, right = 0, (1 << (height - 1)) - 1
for _ in range(height-1):
mid = (left + right) // 2
if index <= mid:
root = root.left
right = mid
else:
root = root.right
left = mid
if not root: return False
return True
left, right = 0, max_nodes_last_level - 1
while left <= right:
mid = (left + right) // 2
if exists(root, mid, height):
left = mid + 1
else:
right = mid - 1
# max_nodes_last_level already represents the count we need
# nodes_above_last_level = max_nodes_last_level - 1
# nodes_last_level = right + 1
return max_nodes_last_level + right