0% found this document useful (0 votes)
38 views1 page

Obst

Uploaded by

Anurag R Swamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views1 page

Obst

Uploaded by

Anurag R Swamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

def optimal_bst(keys, freq):

n = len(keys)
cost = [[0] * n for _ in range(n)]
for i in range(n):
cost[i][i] = freq[i]
for cl in range(2, n + 1):
for i in range(n - cl + 1):
j = i + cl - 1
cost[i][j] = float('inf')
for r in range(i, j + 1):
c = cost[i][r - 1] + (cost[r + 1][j] if r < j else 0) + sum(freq[i:j + 1])
if c < cost[i][j]:
cost[i][j] = c
return cost[0][n - 1]
keys = [10, 12, 16, 21]
freq = [4, 2, 6, 3]
min_cost = optimal_bst(keys, freq)
print("Minimum Cost of Optimal Binary Search Tree:", min_cost)

You might also like