def test_build_binary_tree(self):
     array = [-10, 9, 20, None, None, 15, 7]
     root = build_binary_tree(array)
     in_order_array = []
     in_order(root, in_order_array)
     array.remove(None)
     self.assertEqual(self.list_equal([-10, 9, 20, 15, 7], in_order_array),
                      True)
 def test_build_binary_tree02(self):
     array = [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1]
     root = build_binary_tree(array)
     in_order_array = []
     in_order(root, in_order_array)
     array.remove(None)
     self.assertEqual(
         self.list_equal([5, 4, 11, 7, 2, 8, 13, 4, 1], in_order_array),
         True)
Esempio n. 3
0
def random_binary_tree(max_tree_val, max_tree_size):
    tree_values = [
        random.randint(0, max_tree_val) for i in range(max_tree_size)
    ]
    pytree = None
    for val in tree_values:
        pytree = tree_insert(pytree, val)
    py_pre = pre_order(pytree)
    py_in = in_order(pytree)
    py_post = post_order(pytree)
    return (tree_values, py_pre, py_in, py_post)
Esempio n. 4
0
rithm to create a binary search tree with minimal height.
"""
from binary_tree import BinaryNode, in_order, pre_order, post_order


def minimal_tree(arr):
    if not arr:
        return None
    return do_minimal_tree(arr, 0, len(arr) - 1)


def do_minimal_tree(arr, low, high):
    if low > high:
        return None
    mid = (low + high) // 2

    node = BinaryNode(arr[mid])
    node.left = do_minimal_tree(arr, low, mid - 1)
    node.right = do_minimal_tree(arr, mid + 1, high)

    return node


if __name__ == '__main__':
    tree = minimal_tree([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    in_order(tree, lambda n: print(n.value))
    print('')
    pre_order(tree, lambda n: print(n.value))
    print('')
    post_order(tree, lambda n: print(n.value))
Esempio n. 5
0
from binary_tree import Node, in_order


def helper(start, end):
    if start >= end:
        return [None] if start > end else [Node(start)]
    res = []
    for i in range(start, end):
        left = helper(start, i)
        right = helper(i + 1, end)
        for j in left:
            for k in right:
                node = Node(i)
                node.left = j
                node.right = k
                res.append(node)
    return res


def generate_tree(n):
    return helper(1, n + 1)


if __name__ == '__main__':
    print('leetcode 95')
    for r in generate_tree(3):
        print(in_order(r))