I'm trying to solve the Hackerrank's Insertion Sort Advanced Analysis problem using BST (similar to this question on SO). As I put items in the tree, I need to find out the number of items greater than it (the get_rank()
method in the code):
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
self.num_left_children = 0
self.num_right_children = 0
def insert(self, data):
if data <= self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
self.num_left_children += 1
else:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
self.num_right_children += 1
def get_rank(self, data):
if data < self.data:
return self.num_right_children + self.left.get_rank(data) + 1
elif data > self.data:
return self.right.get_rank(data)
else:
return self.num_right_children
How can I improve the performance of this code (e.g. in case multiple identical items are put into the tree) ?