示例#1
0
class Tree(object):
    from binarytree import heap

    root = heap()
    print('Max-heap of any height : \n', root)

    root2 = heap(height=2)

    print('Max-heap of given height : \n', root2)

    root3 = heap(height=2, is_max=False, is_perfect=True)

    print('Perfect min-heap of given height : \n', root3)
示例#2
0
def test_heap():
    for invalid_height in ['foo', -1]:
        with pytest.raises(ValueError) as err:
            heap(height=invalid_height)
        assert str(err.value) == 'Height must be a non-negative integer'

    # Test heap generation with height of 0
    for _ in range(repetitions):
        root = heap(height=0)
        assert attr(root, 'left') is None
        assert attr(root, 'right') is None
        assert isinstance(attr(root, 'value'), int)
        assert inspect(root)['height'] == 0
        assert inspect(root)['is_min_heap'] is True
        assert inspect(root)['is_max_heap'] is True

    for _ in range(repetitions):
        height = randint(1, 10)
        root = heap(height)
        nodes_to_visit = [root]
        while nodes_to_visit:
            node = nodes_to_visit.pop()
            assert isinstance(node, Node)
            assert isinstance(attr(node, 'value'), int)
            if attr(node, 'left') is not None:
                nodes_to_visit.append(attr(node, 'left'))
            if attr(node, 'right') is not None:
                nodes_to_visit.append(attr(node, 'right'))
        assert inspect(root)['height'] == height
        assert inspect(root)['is_min_heap'] is True

    for _ in range(repetitions):
        height = randint(1, 10)
        root = heap(height, max=True)
        nodes_to_visit = [root]
        while nodes_to_visit:
            node = nodes_to_visit.pop()
            assert isinstance(node, Node)
            assert isinstance(attr(node, 'value'), int)
            if attr(node, 'left') is not None:
                nodes_to_visit.append(attr(node, 'left'))
            if attr(node, 'right') is not None:
                nodes_to_visit.append(attr(node, 'right'))
        assert inspect(root)['height'] == height
        assert inspect(root)['is_max_heap'] is True
def Test():
    A = []
    T = []
    Cases = []
    for i in range(1, 101):
        root = heap(height=2)
        A.append(root)
        Cases.append(i)
    for i in A:
        start = time.time()
        InOrderTraversal(i)
        # PostOrderTraversal(i)
        # PreOrderTraversal(i)
        T.append(time.time() - start)
    plt.plot(Cases, T, "-o")
    plt.xlabel('List Cases')
    plt.ylabel('List Time')
    plt.title('BinaryTreeTraversals')
    plt.show()
示例#4
0
def test_heap_generation():
    for invalid_height in ['foo', -1, None]:
        with pytest.raises(InvalidTreeHeightError) as err:
            heap(height=invalid_height)
        assert str(err.value) == 'The height must be an integer between 0 - 9'

    root = heap(height=0)
    root.validate()
    assert root.height == 0
    assert root.left is None
    assert root.right is None
    assert isinstance(root.value, int)

    for _ in range(REPETITIONS):
        random_height = random.randint(1, 9)
        root = heap(random_height, is_max=True)
        root.validate()
        assert root.is_max_heap is True
        assert root.is_min_heap is False
        assert root.height == random_height

    for _ in range(REPETITIONS):
        random_height = random.randint(1, 9)
        root = heap(random_height, is_max=False)
        root.validate()
        assert root.is_max_heap is False
        assert root.is_min_heap is True
        assert root.height == random_height

    for _ in range(REPETITIONS):
        random_height = random.randint(1, 9)
        root = heap(random_height, is_perfect=True)
        root.validate()
        assert root.is_max_heap is True
        assert root.is_min_heap is False
        assert root.is_perfect is True
        assert root.is_balanced is True
        assert root.is_strict is True
        assert root.height == random_height
示例#5
0
                if depth < mindepth:
                    mindepth = depth
        return mindepth


def minDepth(A):
    q = deque()
    q.append(A)
    curr, nest, level = 1, 0, 1
    while q:
        item = q.popleft()
        curr -= 1
        if not item.right and not item.left:
            return level
        if item.right:
            q.append(item.right)
            nest += 1
        if item.left:
            q.append(item.left)
            nest += 1
        if curr == 0:
            curr, nest = nest, curr
            level += 1


a = bst()
print(a)
#a= {3, 1, -1, -1}
print(minDepth(a))
b = heap()
print(b)
示例#6
0
from binarytree import Node, tree, bst, heap, pprint

# Generate a random binary tree and return its root
my_tree = tree(height=5, balanced=True)

# Generate a random BST and return its root
my_bst = bst(height=5)

# Generate a random max heap and return its root
my_heap = heap(height=3, max=True)

# Pretty print the trees in stdout
#pprint(my_tree)
#pprint(my_bst)
#pprint(my_heap)

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
pprint(root)
示例#7
0
        yield node.value
        if node.left is not None:
            queue.append(node.left)
        if node.right is not None:
            queue.append(node.right)


if __name__ == '__main__':
    # Generate a random binary tree and return its root node.
    my_tree = tree(height=3, is_perfect=False)

    # Generate a random BST and return its root node.
    my_bst = bst(height=3, is_perfect=True)

    # Generate a random max heap and return its root node.
    my_heap = heap(height=3, is_max=True, is_perfect=False)

    # Pretty-print the trees in stdout.
    #print(my_tree)
    #print(my_bst)
    print(my_bst[12].value, my_bst[9].value,
          [my_bst[i].value for i in range(15)])
    del my_bst[9]
    #del my_bst[10]
    del my_bst[12]
    print(my_bst)
    #my_bst.pprint(index=True)
    print(my_bst.inorder)
    #print(my_bst.preorder)
    #print(my_bst.postorder)
    #print(*[n.value for n in my_bst.levelorder])
示例#8
0
from binarytree import tree, bst, heap, build
import networkx as nx

my_tree1 = tree(height=0)
my_tree1list = list(my_tree1)

print(my_tree1list)

print(my_tree1)
my_tree2 = tree(height=1, is_perfect=True)
print(my_tree2.value)
my_tree3 = tree(height=3, is_perfect=False)
my_heap = heap(height=3)
print(my_tree1)
print(my_tree2)
print(my_tree3)
print(my_heap)

root = None
print(root.inorder)

values = [
    10, 12, 14, 24, 39, 50, 54, 62, 67, 92, 134, 153, 161, 162, 167, 171, 172,
    173, 191, 193, 197, 205, 206, 208, 210, 211, 222, 239, 240, 246, 249, 253,
    263, 270, 286, 299, 303, 305, 308, 316, 319, 325, 344, 349, 350, 353, 363,
    365, 371, 395, 414, 437, 453, 459, 463, 489, 500, 503, 512, 514, 515, 516,
    518, 530, 553, 558, 573, 574, 578, 586, 590, 602, 607, 618, 636, 638, 647,
    676, 690, 691, 716, 761, 767, 798, 811, 815, 836, 843, 849, 867, 882, 903,
    919, 921, 943, 948, 958, 959, 980, 997
]
root = build(values)
示例#9
0
            tNodes[index] = newtNode
            if (index % 2):
                parenttNode.left = newtNode
            else:
                parenttNode.right = newtNode
        index += 1

    return tRoot


class Solution(object):
    def levelOrderBotttom(self, root):
        queue = [(root, 0)]
        result = []
        while queue:
            node, level = queue.pop()
            if node:
                if level >= len(result):
                    result.insert(0, [])
                result[-(level + 1)].append(node.val)
                queue.insert(0, (node.left, level + 1))
                queue.insert(0, (node.right, level + 1))
        return result


noderoot = heap(2)
print(noderoot)
tRoot = fromNodetoTreeNode(noderoot)
solver = Solution()
result = solver.levelOrderBotttom(tRoot)
print(result)
示例#10
0
'''
IN MAX HEAP, THE PARENT NODE HAS THE HIGHEST VALUE AND 
DECREASES AS YOU GO DOWN THE BINARY TREE
'''

from binarytree import heap

root = heap(height=3, is_max=True, is_perfect=False)
print('Max-heap of height 3', root)


root2 = heap(height=3, is_max=False, is_perfect=True)
print('Min-heap of height 3', root2)

root3 = heap()