Skip to content

Commit f017c72

Browse files
author
Jimmy Y
committed
Small tweaks
1 parent 3376b8b commit f017c72

File tree

1 file changed

+4
-9
lines changed

1 file changed

+4
-9
lines changed

dynamic_programming/optimal_bst.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,6 @@ def print_binary_search_tree(root, key, i, j, parent, is_left):
4949

5050
def 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.
@@ -66,6 +64,10 @@ def find_optimal_binary_search_tree(nodes):
6664
37 is the right child of key 25.
6765
42 is the right child of key 37.
6866
"""
67+
# Tree nodes must be sorted first, the code below sorts the keys in
68+
# increasing order and rearrange its frequencies accordingly.
69+
nodes.sort(key=lambda node: node.key)
70+
6971
n = len(nodes)
7072

7173
key = [nodes[i].key for i in range(n)]
@@ -103,15 +105,8 @@ def find_optimal_binary_search_tree(nodes):
103105
def main():
104106
# A sample BST
105107
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-
111108
find_optimal_binary_search_tree(nodes)
112109

113110

114111
if __name__ == "__main__":
115-
# import doctest
116-
# doctest.testmod()
117112
main()

0 commit comments

Comments
 (0)