forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
count-nodes-that-are-great-enough.py
51 lines (44 loc) · 1.34 KB
/
count-nodes-that-are-great-enough.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
42
43
44
45
46
47
48
49
50
51
# Time: O(k * h)
# Space: O(k + h)
import bisect
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
pass
# merge sort
class Solution(object):
def countGreatEnoughNodes(self, root, k):
"""
:type root: Optional[TreeNode]
:type k: int
:rtype: int
"""
def merge_at_most_k(a, b):
result = []
i = j = 0
while i < len(a) or j < len(b):
if j == len(b) or (i < len(a) and a[i] < b[j]):
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
if len(result) == k:
break
return result
def merge_sort(node):
if not node:
return []
left, right = merge_sort(node.left), merge_sort(node.right)
smallest_k = merge_at_most_k(left, right)
i = bisect.bisect_left(smallest_k, node.val)
if i == k:
result[0] += 1
else:
smallest_k.insert(i, node.val)
if len(smallest_k) == k+1:
smallest_k.pop()
return smallest_k
result = [0]
merge_sort(root)
return result[0]