forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
count-complete-tree-nodes.py
42 lines (35 loc) · 965 Bytes
/
count-complete-tree-nodes.py
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
# Time: O(h * logn) = O((logn)^2)
# Space: O(1)
class Solution(object):
# @param {TreeNode} root
# @return {integer}
def countNodes(self, root):
if root is None:
return 0
node, level = root, 0
while node.left is not None:
node = node.left
level += 1
# Binary search.
left, right = 2 ** level, 2 ** (level + 1)
while left < right:
mid = left + (right - left) / 2
if not self.exist(root, mid):
right = mid
else:
left = mid + 1
return left - 1
# Check if the nth node exist.
def exist(self, root, n):
k = 1
while k <= n:
k <<= 1
k >>= 2
node = root
while k > 0:
if (n & k) == 0:
node = node.left
else:
node = node.right
k >>= 1
return node is not None