|
| 1 | +# Copyright (c) June 02, 2017 CareerMonk Publications and others. |
| 2 | + |
| 3 | +# Creation Date : 2017-06-02 06:15:46 |
| 4 | +# Last modification : 2017-06-02 |
| 5 | +# Modified by : Narasimha Karumanchi |
| 6 | +# Book Title : Algorithm Design Techniques |
| 7 | +# Warranty : This software is provided "as is" without any |
| 8 | +# warranty; without even the implied warranty of |
| 9 | +# merchantability or fitness for a particular purpose. |
| 10 | + |
| 11 | +def get_OBST(A, F, i, j, level): |
| 12 | + if i > j: |
| 13 | + return 0 |
| 14 | + min_value = float("inf") |
| 15 | + |
| 16 | + for index in range(i, j + 1): |
| 17 | + val = (get_OBST(A, F, i, index - 1, level + 1) # left tree |
| 18 | + + level * F[index] # value at level |
| 19 | + + get_OBST(A, F, index + 1, j, level + 1)) # right tree |
| 20 | + min_value = min(val, min_value) |
| 21 | + |
| 22 | + return min_value |
| 23 | + |
| 24 | +def OBST(A, F): |
| 25 | + return get_OBST(A, F, 0, len(A) - 1, 1) |
| 26 | + |
| 27 | +A = [10, 12, 20, 35, 46] |
| 28 | +F = [34, 8, 50, 21, 16] |
| 29 | +print OBST(A, F) |
0 commit comments