forked from alqamahjsr/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path315_Count_of_Smaller_Numbers_After_Self.py
More file actions
54 lines (43 loc) · 1.34 KB
/
315_Count_of_Smaller_Numbers_After_Self.py
File metadata and controls
54 lines (43 loc) · 1.34 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
# Solution 1: Binary Search Tree
class BinarySearchTreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.count = 1
self.leftTreeSize = 0
class BinarySearchTree(object):
def __init__(self):
self.root = None
def insert(self, val, root):
if not root:
self.root = BinarySearchTreeNode(val)
return 0
if val == root.val:
root.count += 1
return root.leftTreeSize
if val < root.val:
root.leftTreeSize += 1
if not root.left:
root.left = BinarySearchTreeNode(val)
return 0
return self.insert(val, root.left)
if not root.right:
root.right = BinarySearchTreeNode(val)
return root.count + root.leftTreeSize
return root.count + root.leftTreeSize + self.insert(val, root.right)
class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
tree = BinarySearchTree()
counts = []
for i in range(len(nums) - 1, -1, -1):
counts.append(tree.insert(nums[i], tree.root))
return counts[::-1]
sol = Solution()
input = [5,2,6,1]
output = sol.countSmaller(input)
print("Res: ", output)