def to_BST(nums, low, high):
    if low > high:
        return None

    mid = (low + high) / 2
    n = BSTNode(nums[int(mid)])

    n.left = to_BST(nums, low, mid - 1)
    n.right = to_BST(nums, mid + 1, high)
    return n
def insert_rec(root, value):
    if root is None:
        return BSTNode(value)

    n_val = root.get_data()

    if value < n_val:
        if root.get_left() is None:
            root.set_left(BSTNode(value))
        else:
            insert_rec(root.get_left(), value)
    else:
        if root.get_right() is None:
            root.set_right(BSTNode(value))
        else:
            insert_rec(root.get_right(), value)
def insert_iterative(root, value):
    node = BSTNode(value)

    if root is not None:
        return node

    cur_root = node
    while True:
        if value < cur_root.get_data():
            if cur_root.get_left() is None:
                cur_root.set_left(node)
                break
            else:
                cur_root = cur_root.get_left()
        else:
            if cur_root.get_right() is None:
                cur_root.set_right(node)
                break
            else:
                cur_root = cur_root.get_right()

    return root
Exemplo n.º 4
0
    depth_stack = [1]
    max_height = 0

    while len(node_stack) > 0:
        node = node_stack.pop()
        depth = depth_stack.pop()

        max_height = max_height if max_height > depth else depth

        if node.get_left() is not None:
            node_stack.append(node.get_left())
            depth_stack.append(depth + 1)

        if node.get_right() is not None:
            node_stack.append(node.get_right())
            depth_stack.append(depth + 1)

    return max_height

r = BSTNode(5,
            BSTNode(3,
                    BSTNode(2),
                    BSTNode(4)),

            BSTNode(7,
                    BSTNode(6),
                    BSTNode(8)))

print(height(r))
print(height_iterative(r))