Exemplo n.º 1
0
def main():
    one = Node(1, "")
    two = Node(2, "")
    three = Node(3, "")
    four = Node(4, "")
    five = Node(5, "")
    six = Node(6, "")
    seven = Node(7, "")
    eight = Node(8, "")
    nine = Node(9, "")

    one.left = two
    one.right = three

    two.left = four
    two.right = five

    four.left = six
    four.right = seven

    tree = Tree()
    tree.root = one
    tree.levelorder()
    inverted = upside_down(tree)
    inverted.levelorder()
Exemplo n.º 2
0
def main():
    tree = BST()
    lst = [50, 25, 75, 12, 35, 55, 80]
    for _ in lst:
        tree.insert(_, "hello")

    postorder(tree.root)
Exemplo n.º 3
0
def main():
    complete_binary_tree = BST()
    one = Node(1)
    two = Node(2)
    three = Node(3)
    four = Node(4)
    five = Node(5)
    six = Node(6)
    seven = Node(7)

    one.left = two
    one.right = three
    two.left = four
    two.right = five
    three.left = six
    three.right = seven
    complete_binary_tree.root = one
    add_sibling_pointers(complete_binary_tree.root)
    nodes = list(complete_binary_tree.levelorder_nodes())

    # verify the next pointers
    assert one.next is None
    assert two.next is three
    assert three.next is None
    assert four.next is five
    assert five.next is six
    assert six.next is seven
    assert seven.next is None
Exemplo n.º 4
0
def upside_down(tree):
    d = {}
    traverse_left(tree.root, None, d)

    inverted = Tree()
    inverted.root = d['root']
    return inverted
Exemplo n.º 5
0
def test_insert_mulitple_nodes_return_correct_size():
    """Test for multiple node insertion."""
    from bst import Tree
    test_tree = Tree()
    test_values = random.sample(range(100), 10)
    for i in test_values:
        test_tree.insert(i)

    assert test_tree.size() == len(test_values)
Exemplo n.º 6
0
def test_breadth_first_traversal():
    """Test breadth_first traversal."""
    from bst import Tree
    test_list = [10, 7, 5, 9, 12, 11, 13]
    test_tree = Tree(test_list)

    x = test_tree.breadth_first()

    for i in x:
        assert i == [10, 7, 12, 5, 9, 11, 13]
Exemplo n.º 7
0
def test_search_one_node():
    """Test search for one node from inserted list of nodes."""
    from bst import Tree
    test_tree = Tree()
    test_node_list = [1, 2, 3, 4, 5]

    for i in test_node_list:
        test_tree.insert(i)

    assert test_tree.search(test_node_list[2]).data == 3
Exemplo n.º 8
0
def test_search_mulitple_nodes():
    """Test multiple node searches."""
    from bst import Tree
    test_tree = Tree()
    test_values = random.sample(range(100), 10)
    for i in test_values:
        test_tree.insert(i)

    for j in test_values:
        assert test_tree.search(j).data == j
def main():
    N = 22
    arr = sorted([random.randint(1, N * N) for _ in range(N)])
    print arr
    root = balanced_bst_from_sorted_array(arr, 0, len(arr) - 1)
    tree = BST()
    tree.root = root
    tree.pretty_print()

    inorder = [node.key for node in tree.inorder_nodes()]
    assert arr == inorder
Exemplo n.º 10
0
def test():
    from bst import Tree

    x = [10, 33, 1, 5, 65, 3, 25, 167, 34, 6, 15, 28]
    bst = Tree(x[0])
    for val in x[1:]:
        bst.insert(bst.root, val)

    i = BSTIterator(bst.root)
    while i.hasNext():
        print(i.next())
Exemplo n.º 11
0
def test_in_order_one():
    """Test sort one node."""
    from bst import Tree
    test_list = [10]

    test_tree = Tree(test_list)
    path = test_tree.in_order(test_tree.root)

    count = 0
    for i in path:
        assert i.data == test_list[count]
        count += 1
Exemplo n.º 12
0
def main():
    tree = BST()
    N = 11
    _set = set([random.randint(1, N * N) for _ in range(N)])
    # _set = [50, 6, 33, 20, 35, 36]
    for x in _set:
        tree.insert(x, "")

    # just set the root to 0 so the full tree is not BST
    tree.root.key = 0
    tree.pretty_print()
    print "largest bst with nodes: %d" % largest_bst(tree.root)
Exemplo n.º 13
0
def test_in_order_multiple_nodes():
    """Test sort multiple nodes."""
    from bst import Tree
    test_list = [5, 2, 6, 1, 4]
    test_tree = Tree(test_list)
    path = test_tree.in_order(test_tree.root)

    test_results = [1, 2, 4, 5, 6]

    count = 0
    for i in path:
        assert i.data == test_results[count]
        count += 1
Exemplo n.º 14
0
def merge(t1, t2):
    inorder_t1 = []
    inorder_t2 = []

    inorder(t1.root, inorder_t1)
    inorder(t2.root, inorder_t2)

    merged_arr = sorted(inorder_t1 + inorder_t2)
    print_nodes(merged_arr)
    root = balanced_bst_from_sorted_array(merged_arr, 0, len(merged_arr) - 1)

    tree = BST()
    tree.root = root
    return tree
Exemplo n.º 15
0
def test_get_depth_small_tree():
    """Test multiple nodes has depth of 3."""
    from bst import Tree
    test_tree = Tree()
    test_tree.insert(5)
    test_tree.insert(2)
    test_tree.insert(3)
    test_tree.insert(1)
    test_tree.insert(7)

    assert test_tree.get_depth(test_tree.root) == 3
Exemplo n.º 16
0
def balanced_3_nodes():
    """Create balanced tree with 3 nodes."""
    from bst import Tree
    t = Tree()
    t.insert(10)
    t.insert(5)
    t.insert(15)
    return t
Exemplo n.º 17
0
def test_post_order_multiple_nodes():
    """Test postorder on larger tree."""
    from bst import Tree
    test_list = [10, 7, 12, 5, 9, 11, 13, 4]
    test_tree = Tree(test_list)

    test_results = [7, 5, 4, 9, 12, 11, 13, 10]

    path = test_tree.post_order(test_tree.root)

    count = 0

    for i in path:
        assert i.data == test_results[count]
        count += 1
Exemplo n.º 18
0
def main():
    tree = BST()
    N = 10
    _set = set([random.randint(1, N * N) for _ in range(N)])
    for x in _set:
        tree.insert(x, "hello")

    inorder_result = []
    inorder(tree.root, inorder_result)

    iterator_result = []
    iterator = InorderIterator(tree.root)
    while iterator.has_next():
        iterator_result.append(iterator.next().key)
    assert inorder_result == iterator_result
def _to_list(node):

if __name__ == '__main__':
    t = Tree()

    t.add(5)
    t.add(3)
    t.add(4)
    t.add(2)
    t.add(7)
    t.add(6)
    t.add(8)
Exemplo n.º 20
0
def test_if_iterable_is_inserted(bst):
    """Test for iterables."""
    from bst import Tree
    test_iter = [5, 3, 7]
    test_node = Tree(test_iter)
    assert test_node.root.data == test_iter[0]
    assert test_node.root.left.data == test_iter[1]
    assert test_node.root.right.data == test_iter[2]
Exemplo n.º 21
0
 def test_find(self):
     tree = Tree(lt)
     for (k, v) in [(0, "0"), (2, "2"), (2, "3"), (1, "1")]:
         tree.insert(k, v)
     assert tree.find(0) == (0, "0")
     assert tree.find(1) == (1, "1")
     assert tree.find(2) == (2, "3")
Exemplo n.º 22
0
def test_del_root_in_single_node_tree():
    """Test deletion of root in tree of one node."""
    from bst import Tree
    new_bst = Tree()
    new_bst.insert(10)
    new_bst.delete(10)
    assert new_bst.root is None
Exemplo n.º 23
0
def brute_sweep_intersections(segments):
    start = time()
    counter = 0
    status = {
        "upper": 0,
        "lower": 1,
    }
    points = []
    event_queue = Tree(event_lt)
    status_queue = {}
    for segment in segments:
        event_queue.insert(upper_end(*segment), (status["upper"], segment))
        event_queue.insert(lower_end(*segment), (status["lower"], segment))
    while not event_queue.empty():
        (_, (label, segment)) = event_queue.pop()
        if label == status["upper"]:
            for other in list(status_queue.keys()):
                counter += 1
                point = point_of_intersection(segment, other)
                if point is not None:
                    points.append(point)
            status_queue[segment] = None
        else:
            del status_queue[segment]
    print(results(True, counter, not len(points) == len(set(points)), start))
    return (segments, points)
Exemplo n.º 24
0
def main():
    _50 = Node(50, "hello")
    _25 = Node(25, "hello")
    _75 = Node(75, "hello")
    _12 = Node(12, "hello")
    _34 = Node(34, "hello")
    _60 = Node(60, "hello")
    _80 = Node(80, "hello")
    _55 = Node(55, "hello")
    _22 = Node(22, "hello")

    _50.left = _25
    _50.right = _75
    _25.left = _12
    _25.right = _34
    _75.left = _60
    _75.right = _80
    _12.right = _55
    assert False is is_bst(_50)

    _12.right = _22
    assert True is is_bst(_50)

    tree = BST()
    N = 10
    for _ in range(N):
        tree.insert(random.randint(1, 100), "hello")

    assert True is is_bst(tree.root)

    # skewed tree
    tree = BST()
    for n in range(N):
        tree.insert(n, "hello")

    assert True is is_bst(tree.root)

    # skewed tree
    tree = BST()
    for n in range(N, 0, -1):
        tree.insert(n, "hello")

    assert True is is_bst(tree.root)
Exemplo n.º 25
0
def main():
    tree = BST()
    N = 6
    _set = set([random.randint(1, N * N) for _ in range(N)])
    for x in _set:
        tree.insert(x, "")

    tree.pretty_print()
    mirror_image(tree.root)
    print ""
    print "after inverting"
    print ""
    tree.pretty_print()
Exemplo n.º 26
0
def main():
    level = int(sys.argv[1])

    for _ in range(100):
        r_array = list(random.randint(-20, 20) for _ in range(7))
        r_in = ' '.join(map(str, r_array))
        user_out = os.popen('echo "{}" | ./a.out'.format(r_in)).read().strip()
        user_array = list(map(int, user_out.split()))
        print('{}\t->\t{}'.format(r_in, user_out))

        tree = Tree()
        tree.add(r_array)

        if level == 0:
            expected_array = breadth_first_search(tree)
        elif level == 1:
            expected_array = pre_order_search(tree)
        elif level == 2:
            expected_array = post_order_search(tree)
        else:
            raise NotImplementedError

        assert user_array == expected_array, 'expected {}, got {}'.format(
            expected_array, user_array)
Exemplo n.º 27
0
def insert_balanced(num):
    num_of_runs = num
    from bst import Tree
    tree = Tree(50)
    while num_of_runs > 0:
        left_num = LESSER[num_of_runs]
        right_num = GREATER[num_of_runs]
        tree.insert(left_num)
        tree.insert(right_num)
        num_of_runs -= 1
    return tree
Exemplo n.º 28
0
def main():
    tree = BST()
    N = 10
    _set = set([random.randint(1, N * N) for _ in range(N)])
    for x in _set:
        tree.insert(x, "")

    new_root = clone(tree.root)
    new_tree = BST()
    new_tree.root = new_root

    for orig_node, cloned_node in zip(tree.levelorder_nodes(),
                                      new_tree.levelorder_nodes()):
        assert orig_node is not cloned_node
        assert orig_node.key == cloned_node.key
        assert orig_node.data == cloned_node.data
Exemplo n.º 29
0
def main():
    tree = BST()
    N = 10
    _set = set([random.randint(1, N * N) for _ in range(N)])
    for x in _set:
        tree.insert(x, "")

    tree.pretty_print()
    postorder = [node.key for node in tree.postorder_nodes()]
    print postorder
    postorder_iterator = PostorderIterator(tree.root)
    idx = 0
    while postorder_iterator.has_next():
        postorder_iterator.next() is postorder[idx]
        idx += 1
Exemplo n.º 30
0
def get_avg_height(N: int, t: int, print_statements=False) -> float:
    height_sum = 0
    for i in range(t):
        rand = [random.randrange(1, 501) for x in range(N)]
        tree = Tree()
        for x in rand:
            tree.insert(x)

        height_sum += tree.height()
        if print_statements:
            print("The height of the tree with {} nodes is {}".format(
                N, tree.height()))
    avg = height_sum / t
    if print_statements:
        print("The average height is", avg)
    return avg
Exemplo n.º 31
0
def main():
    t1 = BST()

    N = 5
    arr1 = list(set([random.randint(1, 10) for _ in range(N)]))
    arr2 = list(set([random.randint(1, 10) for _ in range(N)]))
    print arr1
    print arr2

    for e in arr1:
        t1.insert(e, "")

    t2 = BST()
    for e in arr2:
        t2.insert(e, "")

    merged_tree = merge(t1, t2)
    inorder_merged = []
    inorder(merged_tree.root, inorder_merged)
    merged_tree.levelorder()
    assert sorted(arr1 + arr2) == [x.key for x in inorder_merged]
def test_contains_true(even):
    from bst import Tree
    tree = Tree(4)
    tree.insert(even)
    assert tree.contains(even)
Exemplo n.º 33
0
        if n1 < root.data and n2 < root.data:
            findLCABST(root.left, n1, n2)
        elif n1 > root.data and n2 > root.data:
            findLCABST(root.left, n1, n2)
        return root


# def findPath(root, n1, n2, arr):
#     lca = findLCABST(root, n1, n2)
#     s1 = Stack()
#     s2 = Stack()
#     if lca.data == n1:
#         s1.push(n1)
#     elif lca.data == n2:
#         s1.push(n2)






if __name__ == '__main__':
    arr = [15, 10, 20, 5, 17, 25, 1, 7, 8]
    tree = Tree()
    tree.create_bst(arr)
    Tree.print_inorder(tree.root)
    print "\n"
    arr = []
    findPath(tree.root, 1, 17, arr)
    print arr
        node = None
    elif node.left is None or node.right is None:
        print "delete case 2"    
        if node.left is not None:
            node.value = node.left.value
            node.left = None
        if node.right is not None:
            node.value = node.right.value
            node.right = None    
    elif node.left is not None and node.right is not None:
         print "delete case 3"    
         inorder_node = inorder_successor(node)
         print inorder_node.value
         node.value = inorder_node.value
         inorder_node.value = 0
            

if __name__ == '__main__':
    t = Tree()

    t.add(5)
    t.add(3)
    t.add(4)
    t.add(1)
    t.add(8)
    t.add(6)

    t.print_tree()
    delete_node(t.get_root(), 5)
    t.print_tree()
    node.value = bst[index]
    print node.value
    index = index + 1
    convert_to_bst(node.right,index)

def to_list(node):
    if node is None:
        return

    to_list(node.left)
    bst.append(node.value)
    to_list(node.right)


if __name__ == '__main__':
    t = Tree()

    t.add(5)
    t.add(3)
    t.add(6)
    t.add(9)
    t.add(2)
    t.add(4)

    t.print_tree()

    to_list(t.get_root())
    qsort(bst)
    index = 0
    convert_to_bst(t.get_root(),index)
Exemplo n.º 36
0
 def setUp(self):
     self.tree = Tree(Node(9))
Exemplo n.º 37
0
def fill_tree(l):
    out = Tree()
    for n in l:
        out.insert(n)
    return out
        return 0
    if node and (node.left is None and node.right is None):
        return 1
    if node is not None:
        height = max(_height(node.left), _height(node.right)) + 1
    else:    
        height = 0

    return height

def height(tree):
    if tree is None:
        return 0

    if tree and (tree.get_root().left is None and tree.get_root().right is None):
        return 1

    return _height(tree.get_root())    

if __name__ == '__main__':
    t1 = Tree()

    t1.add(5)
    t1.add(1)
    t1.add(3)
    t1.add(6)
    t1.add(7)
    t1.add(4)

    print height(t1)
from bst import Tree

def preorder(node):
    
    if node is None:
        return None
    
    print node.value
    preorder(node.left)
    preorder(node.right)

    return


if __name__ == '__main__':
    t = Tree()

    t.add(5)
    t.add(8)
    t.add(2)
    t.add(3)
    t.add(1)
    t.add(6)
    t.add(9)


    t.print_tree()

    print "-- Preorder -- "
    preorder(t.get_root())
    print "-- End -- "
    if current is None:
        return None

    while ((s.is_empty() is not True) or (current is not None)):
        if current is not None:
            s.push(current)
            current = current.left
        else:
            current = s.get_top()
            s.pop()
            print " --> " + str(current.value)
            current = current.right
            

if __name__ == '__main__':

    t = Tree()

    t.add(5)
    t.add(2)
    t.add(4)
    t.add(1)
    t.add(7)
    t.add(6)
    t.add(8)

    t.print_tree()

    inorder(t)
        node.value = 0
    if node is not None:    
        _delete(node.left)
        _delete(node.right)
        node.value = 0

def delete(tree):
    if tree is None:
        return None 

    if tree:
       tree.get_root().value = 0 
    
    _delete(tree.get_root())   

if __name__ == '__main__':
    t1 = Tree()
    t1.add(2)
    t1.add(1)
    t1.add(3)
    t1.add(5)
    t1.add(4)
    t1.add(6)


    t1.print_tree()

    delete(t1)

    t1.print_tree()
Exemplo n.º 42
0
class TreeTestCase(unittest2.TestCase):

    def setUp(self):
        self.tree = Tree(Node(9))


    def tearDown(self):
        self.tree = None


    def test_find_node(self):
        self.assertTrue(self.tree.find_node(9), self.tree.root)
        self.assertFalse(self.tree.find_node(1), self.tree.root)
        self.assertFalse(self.tree.find_node(15), self.tree.root)


    def test_contains(self):
        self.assertFalse(self.tree.contains(1))
        self.assertFalse(self.tree.contains(15))


    def test_insert(self):
        self.tree.insert(Node(6))
        self.assertTrue(self.tree.contains(6))


    def test_delete(self):
        self.tree.insert(Node(13))
        self.tree.insert(Node(7))
        self.assertTrue(self.tree.delete(13))  # leaf
        self.assertTrue(self.tree.delete(7))
        self.assertFalse(self.tree.delete(13))
        self.tree.insert(Node(13))
        self.tree.insert(Node(12))
        self.assertFalse(self.tree.delete(13))


    def test_find_smaller(self):
        self.tree.insert(Node(4))
        self.tree.insert(Node(2))
        self.tree.insert(Node(6))
        self.tree.insert(Node(15))
        self.assertEqual([node.val for node in self.tree.find_smaller(9)], [4, 2, 6])


    def test_find_bigger(self):
        self.tree.insert(Node(22))
        self.tree.insert(Node(18))
        self.tree.insert(Node(25))
        self.assertEqual([node.val for node in self.tree.find_bigger(9)], [22, 25, 18])


    def test_find_min(self):
        self.tree.insert(Node(2))
        self.tree.insert(Node(18))
        self.tree.insert(Node(4))
        self.assertEqual(self.tree.find_min().val, 2)


    def test_find_max(self):
        self.tree.insert(Node(2))
        self.tree.insert(Node(18))
        self.tree.insert(Node(4))
        self.tree.insert(Node(13))
        self.assertEqual(self.tree.find_max().val, 18)


    def test_preorder_traverse(self):
        self.tree.insert(Node(6))
        self.tree.insert(Node(22))
        self.tree.insert(Node(1))
        self.tree.insert(Node(4))
        self.tree.insert(Node(2))
        self.tree.insert(Node(18))
        self.assertEqual([node.val for node in self.tree.preorder_traverse()], [9, 6, 1, 4, 2, 22, 18])


    def test_inorder_traverse(self):
        self.tree.insert(Node(6))
        self.tree.insert(Node(22))
        self.tree.insert(Node(1))
        self.tree.insert(Node(4))
        self.tree.insert(Node(2))
        self.tree.insert(Node(18))
        self.assertEqual([node.val for node in self.tree.inorder_traverse()], [1, 2, 4, 6, 9, 18, 22])


    def test_postorder_traverse(self):
        self.tree.insert(Node(6))
        self.tree.insert(Node(22))
        self.tree.insert(Node(1))
        self.tree.insert(Node(4))
        self.tree.insert(Node(2))
        self.tree.insert(Node(18))
        self.assertSequenceEqual([node.val for node in self.tree.postorder_traverse()], [2, 4, 1, 6, 18, 22, 9])
            return(_is_identical(n1.left,n2.left), _is_identical(n1.right,n2.right))
        else:
            return False

def is_identical(t1, t2):
    if t1 is None and t2 is None:
        return True
    else:
        if t1 is None or t2 is None:
            return False
        else:
            if (t1.get_root().value == t2.get_root().value):
                return (_is_identical(t1.get_root().left,t2.get_root().left) and
                        _is_identical(t1.get_root().right,
                        t2.get_root().right))
    
if __name__ == '__main__': 

    t1 = Tree()
    t2 = Tree()

    t1.add(2)
    t1.add(1)
    t1.add(3)

    t2.add(2)
    t2.add(1)
    t2.add(3)

    print is_identical(t1,None)
def test_contains_false(even, odd):
    from bst import Tree
    tree = Tree(216)
    tree.insert(even)
    assert not tree.contains(odd)
Exemplo n.º 45
0
from bst import Tree

tree = Tree()
tree.add(2)
tree.add(3)
tree.add(1)
tree.print_tree()
        return has_key(node.right, key)

def floor_ceil(node, key, floor, ceil):
    while node:
        if node.value == key:
            floor = node
            ceil = node
        elif key < node.value:
            ceil = node
            node = node.left
        else:
            floor = node
            node = node.right

if __name__=='__main__':

    t = Tree()

    t.add(6)
    t.add(2)
    t.add(3)
    t.add(9)
    t.add(7)

    t.print_tree()

    floor = None
    ceil = None
    floor_ceil(t.get_root(),1,floor,ceil)
    print floor, ceil
Exemplo n.º 47
0
def main():
    """ Example usage """

    # Insert nodes in tree
    tree = Tree(Node(9))  # root node
    tree.insert(Node(6))
    tree.insert(Node(22))
    tree.insert(Node(1))
    tree.insert(Node(4))
    tree.insert(Node(2))
    tree.insert(Node(18))

    """
    Tree after above insertion:
         9
       /   \
      6     22
     /      / 
    1      18
     \
      4
     /
    2

    """

    # Traverse tree
    print('Pre-order traversal:'),
    print(', '.join(str(node.val) for node in  tree.preorder_traverse()))

    print('\nIn-order traversal:'),
    print(', '.join(str(node.val) for node in tree.inorder_traverse()))

    print('\nPost-order traversal:'),
    print(', '.join(str(node.val) for node in tree.postorder_traverse()))

    # Find smallest
    print('\nSmallest:'),
    print(tree.find_min().val)
    
    # Find biggest
    print('\nBiggest:'),
    print(tree.find_max().val)
    
    # Find all smaller than 7
    smaller_than = 7
    print('\nSmaller than {0}:'.format(smaller_than)),
    print(', '.join(str(node.val) for node in tree.find_smaller(smaller_than)))

    # Find all bigger than 5
    bigger_than = 5
    print('\nBigger than {0}:'.format(bigger_than)),
    print(', '.join(str(node.val) for node in tree.find_bigger(bigger_than)))

    # Check if tree contains 4
    contains = 4
    print('\nNode {0} exists in tree == {1}'.format(contains, tree.contains(contains)))

    # Delete leaf node 18
    delete = 18
    print('\nNode {0} was deleted == {1}'.format(delete, tree.delete(delete)))
#/usr/bin/python
from bst import Tree

def min_depth(node):
    if node is None:
        return min_depth 
    if node.left is None and node.right is None:
        return 1
    if node.left is not None:
        min_left = min_depth(node.left)
    if node.right is not None:
        min_right = min_depth(node.right)
    return min(min_left, min_right) + 1


if __name__ == '__main__':
    t = Tree()
    t.add(5)
    t.add(3)
    t.add(2)
    t.add(4)
    t.add(6)


    print min_depth(t.get_root())