def testRemoveLeafNode2(self):
     node_1 = Node(1, None, None)
     node_2 = Node(2, node_1, None)
     node_3 = Node(4, node_2, None)
     node_4 = Node(6, None, None)
     node_5 = Node(5, node_3, node_4)
     bst = BST(node_5)
     bst.removeNode(None, node_5, 1)
     self.assertEquals(node_2.left, None)
 def testRemoveNodeHasOneChildren(self):
     node_1 = Node(1, None, None)
     node_2 = Node(2, node_1, None)
     node_3 = Node(4, node_2, None)
     node_4 = Node(6, None, None)
     node_5 = Node(5, node_3, node_4)
     bst = BST(node_5)
     bst.removeNode(None, node_5, 2)
     self.assertEquals(node_3.left.data, 1)
Example #3
0
def BSTRandomTest(tree, size):
    """
    Fills a BST of a given size, with random elements.
    Tests the contents of the BST with an array, after insertions and deletions.
    Returns Tree if the contents of the BST are identical to the array at all times.
    For BST class and subclass testing.
    """
    passed = True
    ar = []

    # insertions
    for i in range(size):
        v = random.randint(-999, 999)
        if v not in ar:
            ar.append(v)
            tree.insert(Node(v))

    ar.sort()
    if not BSTCompare(tree, ar):
        BSTPrintErrorMessage(tree, ar, ", after insertions")
        passed = False

    # known deletions
    for i in range(len(ar) // 2):
        v = ar[i]
        ar.remove(v)
        n = tree.search(v)
        tree.delete(n)

    if not BSTCompare(tree, ar):
        BSTPrintErrorMessage(tree, ar, ", after known deletions")
        passed = False

    # random deletions
    for i in range(size // 2):
        v = random.randint(-1000, 1000)
        if v in ar:
            ar.remove(v)
        n = tree.search(v)
        tree.delete(n)

    if not BSTCompare(tree, ar):
        BSTPrintErrorMessage(tree, ar, ", after random deletions")
        passed = False

    # additional insertions
    for i in range(size // 4):
        v = random.randint(-1000, 1000)
        if v not in ar:
            ar.append(v)
            tree.insert(Node(v))
    ar.sort()
    if not BSTCompare(tree, ar):
        BSTPrintErrorMessage(tree, ar, ", after second insertions")
        passed = False

    return passed
def main():
    root = Node(1)
    insert(root, Node(0))
    insert(root, Node(2))
    for i in range(0, 9):
        insert(root, Node(random.randint(0, i)))
    levelOrder(root)
    print 'asdf'
    list_level(root, 3)
    pass
Example #5
0
def baltree(root, list):
    if not list:
        return

    mid = len(list) / 2
    root.data = list[mid]

    root.left = Node()
    root.right = Node()

    baltree(root.left, list[0: mid])
    baltree(root.right, list[mid + 1:])
Example #6
0
 def print_Trees(first, last):
     trees = []
     for i in range(first, last + 1):
         for j in print_Trees(first, i - 1):
             for y in print_Trees(i + 1, last):
                 # print("hi")
                 BT = Binary_Tree()
                 root = Node(i)
                 root.left = j
                 root.right = y
                 BT.root = root
                 trees.append(root)
     return trees or [None]
Example #7
0
def main():
    root1 = Node(0)
    root2 = Node(10)
    insert(root2, Node(5))
    insert(root2, Node(7))
    arr = [i for i in range(0, 9)]
    createBstFromSorted(root1, arr, 0, len(arr) - 1)

    levelOrder(root1)
    print 'root2'
    levelOrder(root2)

    print subtree(root1, root2)

    pass
 def testInsertThreeNodes(self):
     node_1 = Node(5, None, None)
     bst = BST(node_1)
     bst.insert(node_1, 4)
     bst.insert(node_1, 2)
     bst.insert(node_1, 1)
     self.assertEquals(node_1.left.left.left.data, 1)
    def test_tree_level_lists(self):
        bst = BstLevelLists(Node(5))
        bst.insert(3)
        bst.insert(8)
        bst.insert(2)
        bst.insert(4)
        bst.insert(1)
        bst.insert(7)
        bst.insert(6)
        bst.insert(9)
        bst.insert(10)
        bst.insert(11)

        levels = bst.create_level_lists()
        results_list = []
        for level in levels:
            results = Results()
            for node in level:
                results.add_result(node)
            results_list.append(results)

        assert_equal(str(results_list[0]), '[5]')
        assert_equal(str(results_list[1]), '[3, 8]')
        assert_equal(str(results_list[2]), '[2, 4, 7, 9]')
        assert_equal(str(results_list[3]), '[1, 6, 10]')
        assert_equal(str(results_list[4]), '[11]')

        print('Success: test_tree_level_lists')
Example #10
0
 def traversal(self, parent: Node, pos: Vector3):
     order = []
     if parent.isLeaf():
         if parent.value:
             order += parent.value
     elif self.determine_observator_location(parent.value[0], pos) == 1:
         if parent.rightNode:
             order += self.traversal(parent.rightNode, pos)
         if parent.value:
             order += parent.value
         if parent.leftNode:
             order += self.traversal(parent.leftNode, pos)
     elif self.determine_observator_location(parent.value[0], pos) == -1:
         if parent.leftNode:
             order += self.traversal(parent.leftNode, pos)
         if parent.value:
             order += parent.value
         if parent.rightNode:
             order += self.traversal(parent.rightNode, pos)
     elif self.determine_observator_location(parent.value[0], pos) == 0:
         if parent.leftNode:
             order += self.traversal(parent.leftNode, pos)
         if parent.rightNode:
             order += self.traversal(parent.rightNode, pos)
     return order
def main():
    root = Node(6)
    left = Node(4)
    right = Node(5)
    l1 = Node(3)
    l2 = Node(5)
    insert(left, l1)
    insert(left, l2)

    insert(root, left)
    insert(root, right)
    levelOrder(root)
    print ancestor(root, l1, l2, [False], [False], [False])
    print 'root is ' + str(left)

    pass
def createBstFromSorted(root, arr, start, end):
    if not root:
        return

    if start > end:
        root = None

        return
    mid = (start + end) / 2
    root.data = arr[mid]

    if not start > (mid - 1):
        root.left = Node()
        createBstFromSorted(root.left, arr, start, mid - 1)
    if not (mid + 1) > end:
        root.right = Node()
        createBstFromSorted(root.right, arr, mid + 1, end)
def main():
    root = Node()

    arr = [i for i in range(0, 7)]
    createBstFromSorted(root, arr, 0, len(arr) - 1)
    levelOrder(root)

    print arr
 def testInsertFourNodes(self):
     node_1 = Node(5, None, None)
     bst = BST(node_1)
     bst.insert(node_1, 4)
     bst.insert(node_1, 2)
     bst.insert(node_1, 1)
     bst.insert(node_1, 6)
     self.assertEquals(node_1.right.data, 6)
    def test_height(self):
        bst = BstHeight(Node(5))
        assert_equal(bst.height(bst.root), 1)
        bst.insert(2)
        bst.insert(8)
        bst.insert(1)
        bst.insert(3)
        assert_equal(bst.height(bst.root), 3)

        print('Success: test_height')
    def test_bfs(self):
        bst = BstBfs(Node(5))
        bst.insert(2)
        bst.insert(8)
        bst.insert(1)
        bst.insert(3)
        bst.bfs(self.results.add_result)
        assert_equal(str(self.results), '[5, 2, 8, 1, 3]')

        print('Success: test_bfs')
Example #17
0
    def test_bst_validate(self):
        bst = BstValidate(Node(5))
        bst.insert(8)
        bst.insert(5)
        bst.insert(6)
        bst.insert(4)
        bst.insert(7)
        assert_equal(bst.validate(), True)

        bst = BstValidate(Node(5))
        left = Node(5)
        right = Node(8)
        invalid = Node(20)
        bst.root.left = left
        bst.root.right = right
        bst.root.left.right = invalid
        assert_equal(bst.validate(), False)

        print('Success: test_bst_validate')
Example #18
0
    def build_tree(self, parent: Node, x=0):
        fronts, behinds, toDivides = self.determine_location(
            parent.value[x], parent.value[0:x] + parent.value[x + 1:])
        if len(toDivides) > 0:
            new_polygons = self.divide_polygons(parent.value[x], toDivides)
            if new_polygons:
                fronts_, behinds_, containingX = self.determine_location(
                    parent.value[x], new_polygons)
                fronts += fronts_
                behinds += behinds_
                parent.value = [parent.value[x]]
                parent.value += containingX

        if len(fronts) > 0:
            parent.addLeftNode(fronts)
            self.build_tree(parent.leftNode)
        if len(behinds) > 0:
            parent.addRigthNode(behinds)
            self.build_tree(parent.rightNode)
Example #19
0
def BSTFromArray(arr):
    """
    Creates a BST from the keys in a given array.
    type arr: List[]
    rtype: BST
    """
    tree = BST()
    for k in arr:
        tree.insert(Node(k))
    return tree
Example #20
0
 def test_bst_second_largest(self):
     bst = Solution(None)
     assert_raises(TypeError, bst.find_second_largest)
     root = Node(10)
     bst = Solution(root)
     node5 = bst.insert(5)
     node15 = bst.insert(15)
     node3 = bst.insert(3)
     node8 = bst.insert(8)
     node12 = bst.insert(12)
     node20 = bst.insert(20)
     node2 = bst.insert(2)
     node4 = bst.insert(4)
     node30 = bst.insert(30)
     assert_equal(bst.find_second_largest(), node20)
     root = Node(10)
     bst = Solution(root)
     node5 = bst.insert(5)
     node3 = bst.insert(3)
     node7 = bst.insert(7)
     assert_equal(bst.find_second_largest(), node7)
     print('Success: test_bst_second_largest')
 def testFoundSearch(self):
     node_5 = Node(5, None, None)
     bst = BST(node_5)
     bst.insert(node_5, 4)
     bst.insert(node_5, 2)
     bst.insert(node_5, 1)
     bst.insert(node_5, 3)
     bst.insert(node_5, 6)
     bst.insert(node_5, 7)
     bst.insert(node_5, 8)
     bst.insert(node_5, 0)
     bst.printAllNodes()
     self.assertTrue(bst.search(node_5, 7))
 def testNotFoundSearch(self):
     node_5 = Node(5, None, None)
     bst = BST(node_5)
     bst.insert(node_5, 4)
     bst.insert(node_5, 2)
     bst.insert(node_5, 1)
     bst.insert(node_5, 3)
     bst.insert(node_5, 6)
     bst.insert(node_5, 7)
     bst.insert(node_5, 8)
     bst.insert(node_5, 0)
     bst = BST(node_5)
     self.assertFalse(bst.search(node_5, 9))
 def testRemoveNodeHasTwoChildrenRightSubtree(self):
     node_5 = Node(5, None, None)
     bst = BST(node_5)
     bst.insert(node_5, 4)
     bst.insert(node_5, 2)
     bst.insert(node_5, 1)
     bst.insert(node_5, 3)
     bst.insert(node_5, 6)
     bst.insert(node_5, 7)
     bst.insert(node_5, 8)
     bst.insert(node_5, 0)
     bst.removeNode(None, node_5, 7)
     self.assertFalse(bst.search(node_5, 7))
Example #24
0
def AVLFullTest():
    for i in range(30):
        tree = AVL()
        passed = BSTRandomTest(tree, 1000)

        if passed:
            height = tree.height()
            arr = tree.inorderWalk()
            max_height = round(1.44 * math.log(len(arr), 2) - 1, 1)
            if height > max_height:
                s = "but height exceeded expectations: "
            else:
                s = "and height within expectations: "
            s += "actual " + str(height) + " vs. expected " + str(max_height)
            print "Passed test", i + 1, s

    tree = AVL()
    ar = []
    for i in range(16):
        v = random.randint(-99, 99)
        if v not in ar:
            tree.insert(Node(v))
            ar.append(v)
    ar.sort()

    print "Height =", tree.height()
    print "Max. expected height =", round(1.44 * math.log(len(ar) + 1, 2) - 1,
                                          1)
    print "Minimum =", tree.minimum()
    print "Maximum =", tree.maximum()
    print "In-order Walk =", tree.inorderWalk()
    print "Array =", ar
    print "Tree ="
    print tree

    for i in range(3):
        index = random.randint(0, len(ar) - 1)
        v = ar[index]
        tree.delete(tree.search(v))
        ar.remove(v)

    print "Height =", tree.height()
    print "Max. expected height =", round(1.44 * math.log(len(ar) + 1, 2) - 1,
                                          1)
    print "Minimum =", tree.minimum()
    print "Maximum =", tree.maximum()
    print "In-order Walk =", tree.inorderWalk()
    print "Array =", ar
    print "Tree ="
    print tree
    def test_dfs(self):
        bst = BstDfs(Node(5))
        bst.insert(2)
        bst.insert(8)
        bst.insert(1)
        bst.insert(3)

        bst.in_order_traversal(bst.root, self.results.add_result)
        assert_equal(str(self.results), "[1, 2, 3, 5, 8]")
        self.results.clear_results()

        bst.pre_order_traversal(bst.root, self.results.add_result)
        assert_equal(str(self.results), "[5, 2, 1, 3, 8]")
        self.results.clear_results()

        bst.post_order_traversal(bst.root, self.results.add_result)
        assert_equal(str(self.results), "[1, 3, 2, 8, 5]")
        self.results.clear_results()

        bst = BstDfs(Node(1))
        bst.insert(2)
        bst.insert(3)
        bst.insert(4)
        bst.insert(5)

        bst.in_order_traversal(bst.root, self.results.add_result)
        assert_equal(str(self.results), "[1, 2, 3, 4, 5]")
        self.results.clear_results()

        bst.pre_order_traversal(bst.root, self.results.add_result)
        assert_equal(str(self.results), "[1, 2, 3, 4, 5]")
        self.results.clear_results()

        bst.post_order_traversal(bst.root, self.results.add_result)
        assert_equal(str(self.results), "[5, 4, 3, 2, 1]")

        print('Success: test_dfs')
Example #26
0
def test_get():
    root = Node('b', 5)
    root.left = Node('a', 3)
    root.right = Node('c', 2)
    bst = BST(root)

    assert bst.get('a') == 3
    assert bst.get('c') == 2
    assert bst.get('d') is None
 def handle_BST(self):
     print "How many nodes would you like to include in the binary search tree?"
     num_nodes = raw_input(">")
     print "Please enter the root node"
     root_node_data = raw_input(">")
     root_node = Node(data=root_node_data,
                      left=None,
                      right=None,
                      is_root=True)
     bst = BST(root_node)
     for i in range(int(num_nodes) - 1):
         print "Please enter node val"
         val = raw_input(">")
         bst.insert(bst.root, val)
     print "Your final binary search tree is, in the form [Current, Left Node, Right Node]\n", bst.printAllNodes(
     )
 def testRemoveNodeHasTwoChildrenLeftSubTree(self):
     node_1 = Node(1, None, None)
     node_6 = Node(3, None, None)
     node_2 = Node(2, node_1, node_6)
     node_3 = Node(4, node_2, None)
     node_4 = Node(6, None, None)
     node_5 = Node(5, node_3, node_4)
     bst = BST(node_5)
     bst.removeNode(None, node_5, 2)
     self.assertEquals(node_3.left.data, 3)
     self.assertEqual(node_3.left.left.data, 1)
 def test_invert_tree(self):
     root = Node(5)
     bst = InverseBst(root)
     node2 = bst.insert(2)
     node3 = bst.insert(3)
     node1 = bst.insert(1)
     node7 = bst.insert(7)
     node6 = bst.insert(6)
     node9 = bst.insert(9)
     result = bst.invert_tree()
     assert_equal(result, root)
     assert_equal(result.left, node7)
     assert_equal(result.right, node2)
     assert_equal(result.left.left, node9)
     assert_equal(result.left.right, node6)
     assert_equal(result.right.left, node3)
     assert_equal(result.right.right, node1)
     print('Success: test_invert_tree')
    def test_bst_successor(self):
        nodes = {}
        node = Node(5)
        nodes[5] = node
        bst = Bst(nodes[5])
        nodes[3] = bst.insert(3)
        nodes[8] = bst.insert(8)
        nodes[2] = bst.insert(2)
        nodes[4] = bst.insert(4)
        nodes[6] = bst.insert(6)
        nodes[12] = bst.insert(12)
        nodes[1] = bst.insert(1)
        nodes[7] = bst.insert(7)
        nodes[10] = bst.insert(10)
        nodes[15] = bst.insert(15)
        nodes[9] = bst.insert(9)

        bst_successor = BstSuccessor()
        assert_equal(bst_successor.get_next(nodes[4]), 5)
        assert_equal(bst_successor.get_next(nodes[5]), 6)
        assert_equal(bst_successor.get_next(nodes[8]), 9)
        assert_equal(bst_successor.get_next(nodes[15]), None)

        print('Success: test_bst_successor')
from BST import Node

def max_sum(root):
	if root is None:
		return 0

	l = max_sum(root.left)
	r = max_sum(root.right)
	max_single = max(max(l,r)+root.key,root.key)
	max_top = max(max_single,l+r+root.key)
	max_sum.res = max(max_sum.res,max_top)
	return max_single

def max_util(root):
	max_sum.res = float("-inf")
	max_sum(root)
	return max_sum.res

root = Node(10)
root.left = Node(2)
root.right   = Node(10)
root.left.left  = Node(20)
root.left.right = Node(1)
root.right.right = Node(-25)
root.right.right.left   = Node(3)
root.right.right.right  = Node(4)

print max_util(root)
Example #32
0
def Insert_rec(root,node):
	if not root:
		root = new_node
	else:
		if node.key > root.key:
			if root.right is None:
				root.right = node
			else:
				Insert_rec(root.right,node)
		else:
			if root.left is None:
				root.left = node
			else:
				Insert_rec(root.left,node)

root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(4)
root.left.right = Node(12)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
 
n1 = 10 ; n2 = 14
t = lca(root, n1, n2)
print "LCA of %d and %d is %d" %(n1, n2, t.key)
 
n1 = 14 ; n2 = 8
t = lca(root, n1, n2)
print "LCA of %d and %d is %d" %(n1, n2 , t.key)
 
Example #33
0
from BST import Node

def inorder(root,arr):
	if root:
		inorder(root.left,arr)
		arr.append(root.key)
		inorder(root.right,arr)

def isBST(root):
	arr = []
	inorder(root,arr)
	return arr == sorted(arr)

root = Node(6)
root.left = Node(9)
root.right = Node(10)
root.left.left = Node(17)
root.left.right = Node(4)
root.right.right = Node(11)

print isBST(root)

root = Node(6)
root.left = Node(4)
root.right = Node(7)

print isBST(root)