This earlier question询问有多少种方法可以将值1 - 7插入到二叉搜索树中,从而产生以下树:
4
/ \
2 6
/ \ / \
1 3 5 7
(顺便说一句,答案是80)。
更一般地假设您获得了一个包含某些值的任意BST,并且想知道有多少种可能的方法将这些值插入到最终会产生结果树的BST中。有没有一种有效的算法来确定这个?
谢谢!
答案 0 :(得分:1)
这是一个有趣的问题。我在python中实现了这个想法,这个递归和记忆具有相当不错的性能。 “seq”是唯一整数的输入列表
def answer(seq):
from math import factorial
BStore = dict() # store binomsial coefficient
Store = dict() # store the recusion step
def TreeGenerator(a,L): # for a given number a and a list L, this functions returns the left tree (a list) and the right tree (a list)
LT = []
RT = []
for i in L:
if i<a:
LT.append(i)
else:
RT.append(i)
solution = [LT,RT]
return(solution)
def binomial_coefficient(n, k):
d = n - k
if d < 0:
return(0)
return(factorial(n) / factorial(k) / factorial(d))
def binomial(n, k):
if (n, k) in BStore:
return(BStore[n, k])
else:
solution = binomial_coefficient(n, k)
BStore[n, k] = solution
return(solution)
def R(S): # recursion starts here
if tuple(S) in Store:
return(Store[tuple(S)])
else:
if len(S)<2:
results = 1
else:
a = S[0]
S = S[1:]
Tree = TreeGenerator(a,S)
R1 = R(Tree[0])
R2 = R(Tree[1])
results = binomial(len(R1)+len(R2), len(R2))*R1*R2
Store[tuple(S)] = results
return(results)
return(R(seq))