Exemple #1
0
    queue = []
    queue.append(t1)
    while len(queue):
        node = queue.pop(0)
        if node.data == t2.data:
            if isIdenticalTrees(node, t2):
                return True
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)
    return False


t1 = BinarySearchTree()
t1.insertRecursive(4)
t1.insertRecursive(2)
t1.insertRecursive(3)
t1.insertRecursive(1)
t1.insertRecursive(6)
t1.insertRecursive(5)
t1.insertRecursive(7)
t1.insertRecursive(8)

bst = BinarySearchTree()
bst.insertRecursive(6)
bst.insertRecursive(5)
bst.insertRecursive(7)
bst.insertRecursive(8)

print(isSubtree(t1.root, bst.root))
Exemple #2
0
from BinarySearchTree import BinarySearchTree


def isBST(root, mini, maxi):
    if not root:
        return True

    if mini and root.data <= mini or maxi and root.data > maxi:
        return False

    if not isBST(root.left, mini, root.data) or not isBST(
            root.right, root.data, maxi):
        return False
    return True


bst = BinarySearchTree()
bst.insertRecursive(10)
bst.insertRecursive(-5)
bst.insertRecursive(30)
bst.insertRecursive(-10)
bst.insertRecursive(0)
bst.insertRecursive(36)
bst.insertRecursive(5)

print(isBST(bst.root, None, None))
Exemple #3
0
        return has_node(root.left, val)

    if not root or not has_node(root, a) or not has_node(root, b):
        return None

    def fca(root, a, b):
        curr = root.data
        if curr == a and curr == b:
            return curr
        elif curr < a and curr < b:
            return fca(root.right, a, b)
        elif curr > a and curr > b:
            return fca(root.left, a, b)
        return curr

    return fca(root, a, b)


bst = BinarySearchTree()
bst.insertRecursive(4)
bst.insertRecursive(2)
bst.insertRecursive(3)
bst.insertRecursive(1)
bst.insertRecursive(6)
bst.insertRecursive(5)
bst.insertRecursive(7)
bst.insertRecursive(8)

# print(fca_v2(bst.root, 5, 20))
print(fca_for_bst(bst.root, 3, 1))