CONSTRUCT-OPTIMAL-BST(root, i, j, fa) if i == j - 1 name = "d" + i else name = "k" + root[i, j] if fa == 0 print name + "is the root" else if j < fa print name + "is the left child of" + " k" + fa else print name + "is the right child of" + " k" + fa if j >= i CONSTRUCT-OPTIMAL-BST(root, i, root[i, j] - 1, root[i, j]) CONSTRUCT-OPTIMAL-BST(root, root[i, j] + 1, j, root[i, j])
OPTIMAL-BST(p, q, n) let e[1 : n + 1, 0 : n], w[1 : n + 1, 0 : n], and root[1 : n, 1 : n] be new tables for i = 1 to n + 1 // base cases e[i, i − 1] = qi−1 // equation (14.14) w[i, i − 1] = qi−1 // 为了避免出错,只有一个非根节点时同样单独处理。 for i = 1 to n e[i, i] = qi-1 + pi + qi w[i, i] = e[i, i] + qi-1 + qi root[i, i] = i for l = 2 to n for i = 1 to n − l + 1 j = i + l − 1 e[i, j] = ∞ w[i, j] = w[i, j − 1] + pj + qj // equation (14.15) // 修改之处。 for r = root[i, j - 1] to root[i + 1, j] // try all possible roots r t = e[i, r − 1] + e[r + 1, j] + w[i, j] // equation (14.14) if t < e[i, j] // new minimum? e[i, j] = t root[i, j] = r return e and root