@@ -49,15 +49,11 @@ def print_binary_search_tree(root, key, i, j, parent, is_left):
4949
5050def find_optimal_binary_search_tree (nodes ):
5151 """
52- Precondition: Node keys are sorted in an increasing order.
53-
5452 This function calculates and prints the optimal BST.
5553 The dynamic programming algorithm below runs in O(n^2) time.
5654 Implemented from CLRS book.
5755
58- >>> nodes = [Node(12, 8), Node(10, 34), Node(20, 50), Node(42, 3), Node(25, 40), Node(37, 30)]
59- >>> nodes.sort(key=lambda node: node.key)
60- >>> find_optimal_binary_search_tree(nodes)
56+ >>> find_optimal_binary_search_tree([Node(12, 8), Node(10, 34), Node(20, 50), Node(42, 3), Node(25, 40), Node(37, 30)])
6157 The cost of optimal BST is 324.
6258 20 is the root of the BST.
6359 10 is the left child of key 20.
@@ -66,6 +62,10 @@ def find_optimal_binary_search_tree(nodes):
6662 37 is the right child of key 25.
6763 42 is the right child of key 37.
6864 """
65+ # Tree nodes must be sorted first, the code below sorts the keys in
66+ # increasing order and rearrange its frequencies accordingly.
67+ nodes .sort (key = lambda node : node .key )
68+
6969 n = len (nodes )
7070
7171 key = [nodes [i ].key for i in range (n )]
@@ -103,15 +103,8 @@ def find_optimal_binary_search_tree(nodes):
103103def main ():
104104 # A sample BST
105105 nodes = [Node (i , randint (1 , 50 )) for i in range (10 , 0 , - 1 )]
106-
107- # Tree nodes must be sorted first, the code below sorts the keys in
108- # increasing order and rearrange its frequencies accordingly.
109- nodes .sort (key = lambda node : node .key )
110-
111106 find_optimal_binary_search_tree (nodes )
112107
113108
114109if __name__ == "__main__" :
115- # import doctest
116- # doctest.testmod()
117110 main ()
0 commit comments