Ejemplo n.º 1
0
from binarytree import BinaryTreeNode

def is_bst(root: BinaryTreeNode) -> bool:
    upper_bound = float('inf')
    lower_bound = -float('inf')
    return is_bst_helper(root, upper_bound, lower_bound)


def is_bst_helper(root: BinaryTreeNode, upper_bound: float, lower_bound: float) -> bool:
    if root is None:
        return True
    if root.value > lower_bound and root.value < upper_bound:
        return is_bst_helper(root.left, root.value, lower_bound) and is_bst_helper(root.right, upper_bound, root.value)
    return False


bst = BinaryTreeNode(5)
bst.insert_left(4)
bst.insert_right(6)
bst.right.insert_right(7)

print(is_bst(bst))

badBst = BinaryTreeNode(7)
badBst.insert_left(6)
badBst.insert_right(15)
badBst.left.insert_right(8) # bad value -- bigger than root

print(is_bst(badBst))
Ejemplo n.º 2
0
def second_largest(root: BinaryTreeNode) -> BinaryTreeNode:
    node = root
    parent = root
    while node.right is not None:
        parent = node
        node = node.right
    if node.left is None:
        return parent
    else:
        node = node.left
        while node.right is not None:
            node = node.right
        return node

no_left_bst = BinaryTreeNode(5)
no_left_bst.insert_left(4)
no_left_bst.insert_right(6)
no_left_bst.right.insert_right(7)

print(second_largest(no_left_bst).value)

left_bst = BinaryTreeNode(5)
left_bst.left = BinaryTreeNode(3)
left_bst.right = BinaryTreeNode(8)
left_bst.right.left = BinaryTreeNode(7)
left_bst.right.right = BinaryTreeNode(12) #largest
left_bst.right.right.left = BinaryTreeNode(10) #left tree of largest
left_bst.right.right.left.left = BinaryTreeNode(9)
left_bst.right.right.left.right = BinaryTreeNode(11) #second largest

print(second_largest(left_bst).value)