-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_0222_CountCompleteTreeNodes.py
More file actions
55 lines (46 loc) · 1.41 KB
/
_0222_CountCompleteTreeNodes.py
File metadata and controls
55 lines (46 loc) · 1.41 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
50
51
52
53
54
55
#-----------------------------------------------------------------------------
# Runtime: 80ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import sys, queue
sys.path.append('LeetCode')
from TreeNode import TreeNode
class Solution:
def compute_depth(self, node: TreeNode) -> int:
d = 0
while node.left:
node = node.left
d += 1
return d
def exists(self, idx: int, d: int, node: TreeNode) -> bool:
left, right = 0, 2 ** d - 1
for _ in range(d):
pivot = left + (right - left) // 2
if idx <= pivot:
node = node.left
right = pivot
else:
node = node.right
left = pivot + 1
return node is not None
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
d = self.compute_depth(root)
if d == 0:
return 1
left, right = 1, 2 ** d - 1
while left <= right:
pivot = left + (right - left) // 2
if self.exists(pivot, d, root):
left = pivot + 1
else:
right = pivot - 1
return (2 ** d - 1) + left