Exemplo n.º 1
0
def test_breadth_first_binarytree_with_letters():
    tree = BinaryTree()
    tree._root = _Node(8)
    tree._root.left = _Node("a")
    tree._root.right = _Node(-2)
    assert BinaryTree.breadth_first(tree) == [8, "a", -2]
    tree._root.left.left = _Node(195)
    tree._root.left.right = _Node("cat")
    tree._root.right.right = _Node(8)
    tree._root.left.left.left = _Node(-0.56)
    tree._root.left.left.right = _Node(9)
    tree._root.right.right.right = _Node(23)
    tree._root.right.right.right.left = _Node([5, 7])
    assert BinaryTree.breadth_first(tree) == [
        8, "a", -2, 195, "cat", 8, -0.56, 9, 23, [5, 7]
    ]
Exemplo n.º 2
0
from tree import BinaryTree, Node

top_view = []


def inorder(node):
    if not node.left and not node.right:
        top_view.append(node._data)
    else:
        inorder(node.left)
        inorder(node.right)


if __name__ == '__main__':
    bt = BinaryTree()
    bt._root = Node(20)
    bt._root.left = Node(8)
    bt._root.right = Node(22)
    bt._root.left.left = Node(5)
    bt._root.left.right = Node(3)
    bt._root.right.left = Node(4)
    bt._root.right.right = Node(25)
    bt._root.left.right.left = Node(10)
    bt._root.left.right.right = Node(14)
    inorder(bt._root)
    print(top_view)
Exemplo n.º 3
0
from tree import BinaryTree, Node

top_view = dict()


def traverse_tree(node, horizontal_distance, depth_current):
    if node:
        if horizontal_distance in top_view:
            node_value, depth_old = top_view[horizontal_distance]
            if depth_old > depth_current:
                # this is the higher node
                top_view[horizontal_distance] = (node._data, depth_current)
        else:
            top_view[horizontal_distance] = (node._data, depth_current)
        traverse_tree(node.left, horizontal_distance - 1, depth_current + 1)
        traverse_tree(node.right, horizontal_distance + 1, depth_current + 1)


if __name__ == '__main__':
    tree_one = BinaryTree()
    tree_one._root = Node(1)
    tree_one._root.left = Node(2)
    tree_one._root.right = Node(3)
    tree_one._root.left.right = Node(4)
    tree_one._root.left.right.right = Node(5)
    tree_one._root.left.right.right.right = Node(6)
    traverse_tree(tree_one._root, 0, 1)
    for x in sorted(top_view):
        print(top_view[x][0])
Exemplo n.º 4
0
def test_breadth_first_binarytree_one_element():
    tree = BinaryTree()
    tree._root = _Node(8)
    assert BinaryTree.breadth_first(tree) == [8]