Skip to content

Commit 818a849

Browse files
authored
Update count-complete-tree-nodes.py
1 parent 0d1da1e commit 818a849

File tree

1 file changed

+61
-31
lines changed

1 file changed

+61
-31
lines changed

Python/count-complete-tree-nodes.py

Lines changed: 61 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,72 @@
1-
# Time: O(h * logn) = O((logn)^2)
1+
# Time: O(h * h) = O((logn)^2)
22
# Space: O(1)
33

4+
# Definition for a binary tree node.
5+
class TreeNode(object):
6+
def __init__(self, val=0, left=None, right=None):
7+
pass
8+
9+
410
class Solution(object):
5-
# @param {TreeNode} root
6-
# @return {integer}
711
def countNodes(self, root):
8-
if root is None:
12+
"""
13+
:type root: TreeNode
14+
:rtype: int
15+
"""
16+
def height(root):
17+
h = -1
18+
while root:
19+
h += 1
20+
root = root.left
21+
return h
22+
23+
result, h = 0, height(root)
24+
while root:
25+
if height(root.right) == h-1:
26+
result += 2**h
27+
root = root.right
28+
else:
29+
result += 2**(h-1)
30+
root = root.left
31+
h -= 1
32+
return result
33+
34+
35+
# Time: O(h * logn) = O((logn)^2)
36+
# Space: O(1)
37+
class Solution2(object):
38+
def countNodes(self, root):
39+
"""
40+
:type root: TreeNode
41+
:rtype: int
42+
"""
43+
def check(node, n):
44+
base = 1
45+
while base <= n:
46+
base <<= 1
47+
base >>= 2
48+
49+
while base:
50+
if (n & base) == 0:
51+
node = node.left
52+
else:
53+
node = node.right
54+
base >>= 1
55+
return bool(node)
56+
57+
if not root:
958
return 0
1059

1160
node, level = root, 0
12-
while node.left is not None:
61+
while node.left:
1362
node = node.left
1463
level += 1
1564

16-
# Binary search.
17-
left, right = 2 ** level, 2 ** (level + 1)
18-
while left < right:
19-
mid = left + (right - left) / 2
20-
if not self.exist(root, mid):
21-
right = mid
22-
else:
23-
left = mid + 1
24-
25-
return left - 1
26-
27-
# Check if the nth node exist.
28-
def exist(self, root, n):
29-
k = 1
30-
while k <= n:
31-
k <<= 1
32-
k >>= 2
33-
34-
node = root
35-
while k > 0:
36-
if (n & k) == 0:
37-
node = node.left
65+
left, right = 2**level, 2**(level+1)-1
66+
while left <= right:
67+
mid = left+(right-left)//2
68+
if not check(root, mid):
69+
right = mid-1
3870
else:
39-
node = node.right
40-
k >>= 1
41-
return node is not None
42-
71+
left = mid+1
72+
return right

0 commit comments

Comments
 (0)