コード例 #1
0
def find_ancestor2(tree, n1, n2):
    if not tree:
        return False

    if n1 <= tree.item and n2 >= tree.item or (not tree.left
                                               and not tree.right):
        return tree.item

    if tree.left and (n1 < tree.item and n2 < tree.item):
        return find_ancestor(tree.left, n1, n2) or tree.item

    if tree.right and (n1 > tree.item and n2 > tree.item):
        return find_ancestor(tree.right, n1, n2) or tree.item


if __name__ == '__main__':
    bst = BST()
    l = [10, 5, 6, 3, 8, 2, 1, 11, 9, 4]
    for i in l:
        bst.add(i)
    nodes = bst.preorder_array()

    print 'Original:    ', l
    print 'Preorder:    ', nodes

    print 'Method 1: '
    print 'Ancestor for 3, 11:', find_ancestor(nodes, 3, 11)

    print 'Method 2: '
    print 'Ancestor for 3, 11: ', find_ancestor2(bst.root, 3, 11)
    if node.left:
        if node.left.item > node.item or node.left.item > max_node:
            left = False
        else:
            max_node = node.item
            left = isBST(node.left, max_node, min_node)

    if node.right:
        if node.right.item < node.item or node.right.item < min_node:
            rihjt = False
        else:
            min_node = node.item
            right = isBST(node.right, max_node, min_node)

    return left and right


if __name__ == "__main__":
    bt = BST()
    for i in range(1, 10):
        bt.add(i)

    assert isBST(bt.root) == True

    bt = BT()
    for i in range(1, 10):
        bt.add(i)

    assert isBST(bt.root) == False
コード例 #3
0
#!/usr/bin/env python

__author__ = "bt3"

from binary_search_tree import BST, Node
from binary_tree import BT, Node


def isBalanced(node, left=0, right=0):
    if not node:
        return (left - right) < 2

    return isBalanced(node.left, left+1, right) and \
        isBalanced(node.right, left, right+1)


if __name__ == '__main__':
    bt = BST()
    for i in range(1, 10):
        bt.add(i)

    assert (isBalanced(bt.root) == True)

    bt = BT()
    for i in range(1, 10):
        bt.add(i)

    assert (isBalanced(bt.root) == False)
コード例 #4
0

if __name__ == '__main__':


    # bt
    bt = BT()
    l = [10, 5, 6, 3, 8, 2, 1, 11, 9, 4]
    for i in l:
        bt.add(i)
    print 'BT...'
    print 'Original:    ', l
    print 'Preorder:    ', preorder(bt.root)
    print 'Postorder:   ', postorder(bt.root)
    print 'Inorder:     ', inorder(bt.root)
    print 'Breath:      ', BFT(bt)

    # bst
    bst = BST()
    l = [10, 5, 6, 3, 8, 2, 1, 11, 9, 4]
    for i in l:
        bst.add(i)

    print
    print 'BST ...'
    print 'Original:    ', l
    print 'Preorder:    ', preorder(bst.root)
    print 'Postorder:   ', postorder(bst.root)
    print 'Inorder:     ', inorder(bst.root)
    print 'Breath:      ', BFT(bst)