I have a similar problem to this one. Given a certain insertion sequence which produces a BST, I need to count how many insertion sequences (including the one given) produce the same BST.
The main difference is that my solution needs to allow for duplicate keys (I could only find solutions where all keys must be distinct). It is specified in the problem that keys equal to the current key always go in the left subtree (along with keys which are lesser).
My code so far (heavily inspired by the accepted answer of the linked problem, which seems to work where keys are distinct):
def num_orders(lst):
if len(lst) <= 1:
return 1
num_remaining = len(lst)-1
left_subtree = []
right_subtree = []
for a in lst[1:]:
if a < lst[0]:
left_subtree.append(a)
if a > lst[0]:
right_subtree.append(a)
return num_orders(left_subtree)*num_orders(right_subtree)*nCr(num_remaining,len(left_subtree))
How can I modify this code to allow for duplicate keys?