Beispiel #1
0
 def test_create_triangle(self):
     root_node = Node(data='a')
     left_node = root_node.add_left(data='b')
     right_node = root_node.add_right(data='c')
     self.assertIs(left_node.parent, right_node.parent)
     self.assertIs(left_node.sibling, right_node)
     self.assertIs(right_node.sibling, left_node)
     self.assertIs(root_node.right, right_node)
     self.assertIs(root_node.left, left_node)
Beispiel #2
0
def construct_tree(cumsum, l, h):
    if h - l < 1:
        return

    if h - l == 1:
        return Node(w[l], 0, f[l])

    t = (cumsum[l] + cumsum[h - 1]) // 2
    mid = find_balance(cumsum, t, l, h)
    root = Node(w[mid], 0, f[mid])
    left_sub = construct_tree(cumsum, l, mid)
    if left_sub:
        root.add_left(left_sub)

    right_sub = construct_tree(cumsum, mid + 1, h)
    if right_sub:
        root.add_right(right_sub)

    return root
Beispiel #3
0
            # print("name", tbl_root[i][j-1].key, "value", left)
            for m in range(left, down + 1):
                cost = sum([
                    cost_lookup(tbl_cost, i, m - 1),
                    cost_lookup(tbl_cost, m + 1, j),
                    sum_lookup(tbl_sum, i, j)
                ])
                if cost < tbl_cost[i][j]:
                    tbl_cost[i][j] = cost
                    min_r = m

            new_root = Node(w[min_r], min_r, f[min_r])
            tbl_root[i][j] = new_root
            if min_r - 1 >= i:
                left_root = tbl_root[i][min_r - 1]
                new_root.add_left(left_root)

            if min_r + 1 <= j:
                right_root = tbl_root[min_r + 1][j]
                new_root.add_right(right_root)

                # printTable(tbl_cost)

    m_tree = tbl_root[0][l - 1]
    assert m_tree.check_invariant()
    # print(m_tree.ascii_art())
    # printTable(tbl_cost)
    total = tbl_sum[0][l - 1]
    lst = []
    in_order(lst, m_tree, 1)
    cumsum = 0