1
1
#!/usr/bin/python3
2
2
3
3
# This Python program provides O(n^2) dynamic programming solution
4
- # to an optimal BST problem.
4
+ # to an optimal binary search tree (abbreviated BST) problem.
5
5
#
6
6
# The goal of the optimal BST problem is to build a low-cost BST for a
7
7
# given set of nodes, each with its own key and frequency. The frequency
@@ -25,7 +25,7 @@ def __init__(self, key, freq):
25
25
self .freq = freq
26
26
27
27
28
- def print_BST (root , key , i , j , parent , is_left ):
28
+ def print_binary_search_tree (root , key , i , j , parent , is_left ):
29
29
"""Recursive function to print a BST from a root table."""
30
30
if i > j or i < 0 or j > len (root ) - 1 :
31
31
return
@@ -39,15 +39,15 @@ def print_BST(root, key, i, j, parent, is_left):
39
39
else :
40
40
print (f"{ key [root [i ][j ]]} is the right child of key { parent } ." )
41
41
42
- print_BST (
42
+ print_binary_search_tree (
43
43
root , key , i , root [i ][j ] - 1 , key [root [i ][j ]], True
44
44
) # recur to left child
45
- print_BST (
45
+ print_binary_search_tree (
46
46
root , key , root [i ][j ] + 1 , j , key [root [i ][j ]], False
47
47
) # recur to right child
48
48
49
49
50
- def find_optimal_BST (nodes ):
50
+ def find_optimal_binary_search_tree (nodes ):
51
51
"""
52
52
Precondition: Node keys are sorted in an increasing order.
53
53
@@ -97,7 +97,7 @@ def find_optimal_BST(nodes):
97
97
root [i ][j ] = r
98
98
99
99
print (f"The cost of optimal BST is { dp [0 ][n - 1 ]} ." )
100
- print_BST (root , key , 0 , n - 1 , - 1 , False )
100
+ print_binary_search_tree (root , key , 0 , n - 1 , - 1 , False )
101
101
102
102
103
103
def main ():
@@ -108,7 +108,7 @@ def main():
108
108
# increasing order and rearrange its frequencies accordingly.
109
109
nodes .sort (key = lambda node : node .key )
110
110
111
- find_optimal_BST (nodes )
111
+ find_optimal_binary_search_tree (nodes )
112
112
113
113
114
114
if __name__ == "__main__" :
0 commit comments