Beispiel #1
0
def build_minimal_bst(array, start, end):
    """Build a minimal height binary search tree given a sorted arry.
    Child trees have equal size, so the resulted bst might not be complete.
    """
    if start >= end:
        return None
    mid = (start + end) // 2
    root = Node(array[mid])
    root.left = build_minimal_bst(array, start, mid)
    root.right = build_minimal_bst(array, mid + 1, end)
    return root
def build_minimal_bst(array, start, end):
    """Build a minimal height binary search tree given a sorted arry.
    Child trees have equal size, so the resulted bst might not be complete.
    """
    if start >= end:
        return None
    mid = (start + end) // 2
    root = Node(array[mid])
    root.left = build_minimal_bst(array, start, mid)
    root.right = build_minimal_bst(array, mid + 1, end)
    return root
Beispiel #3
0
def build_complete_bst(array, start, end):
    """Build a complete binary search tree given a sorted array."""
    if start >= end:
        return None
    # find the root node index in the given array
    l = end - start
    height = int(math.log(l, 2))
    num_of_leafs = l - (2**height - 1)
    if num_of_leafs > 2**(height - 1):
        left_tree_size = 2**height - 1
    else:
        left_tree_size = l - 2**(height - 1)
    root_index = start + left_tree_size
    # recursively build bst
    root = Node(array[root_index])
    root.left = build_complete_bst(array, start, root_index)
    root.right = build_complete_bst(array, root_index + 1, end)
    return root
def build_complete_bst(array, start, end):
    """Build a complete binary search tree given a sorted array."""
    if start >= end:
        return None
    # find the root node index in the given array
    l = end - start
    height = int(math.log(l, 2))
    num_of_leafs = l - (2 ** height - 1)
    if num_of_leafs > 2 ** (height - 1):
        left_tree_size = 2 ** height - 1
    else:
        left_tree_size = l - 2 ** (height - 1)
    root_index = start + left_tree_size
    # recursively build bst
    root = Node(array[root_index])
    root.left = build_complete_bst(array, start, root_index)
    root.right = build_complete_bst(array, root_index + 1, end)
    return root