Example #1
0
    def test_basic(self):
        bin = BST()
        bin.insert(5)
        self.assertEqual(bin.root.val, 5)

        bin.insert(6)
        self.assertEqual(bin.root.right.val, 6)
Example #2
0
def full_tree():
    test_tree = BST()
    test_tree.insert(5)
    test_tree.insert(8)
    test_tree.insert(3)
    test_tree.insert(4)
    return test_tree
Example #3
0
def main(argv):
    #create a new tree
    tree = BST()



    #open file argument
    file = open(argv[1], "r")
    # goes for amount of of lines in f
    for line in file:
        text = line.split()
        #test cases for what the first element in the list is
        if text[0] == "insert":
            #saves the second element, since it exists
            data = text[1]
            tree.insert(data)
        elif text[0] == "delete":
            #saves element, then calls delete
            data = text[1]
            tree.delete(data)
        elif text[0] == "preorder" or text[0] == "postorder" or text[0] == "inorder":
            #tests for if a traverse then calls the function
            tree.traverse(text[0], tree.getRoot())
        else:
            print("incorrect format")

    return 0
Example #4
0
def test_preorder():
    for i in range(20):
        bst = BST()
        randomlist = random.sample(range(1, 100), 35)
        for x in randomlist:
            bst.insert(x)
        assert bst.preorder(bst.root) == bst.preorder_iterative()
Example #5
0
def main():
    #create BST:
    print('create BST with elements: 10, 5, 2, 6, 1, 4, 20, 15, 25')
    bst = BST(10)
    insert_in_BST = [5, 2, 6, 1, 4, 20, 15, 25]
    for item in insert_in_BST:
        bst.insert(item)

    # test find() -> find root with key = 2 and print key:
    print('find root with key=2 and print key:')
    print(bst.find(2).key)

    # find min/max:
    print('find node with min key and print key (should be 1):')
    print(bst.findMin().key)
    print('find node with max key and print key (should be 25):')
    print(bst.findMax().key)

    # traverse tree / delete nodes:
    print('traverse tree in order and print all keys:')
    bst.traverseInOrder()
    print('delete node with key=5 and traverse tree again:')
    bst.delete(5)
    bst.traverseInOrder()

    # get root and print it's key:
    print('get root key (should be 10)')
    print(bst.getRoot().key)
Example #6
0
def main(argv):
    myBST = BST()

    # Loop over input file (filename passed via argv).
    input_file = argv[1]
    with open(input_file, 'r') as file_ob:
        # Split each line into a task and number (if one exists)
        #hint: use the split method for strings
        # Perform the function corresponding to the specified task
        # i.e., insert, delete, inorder, preorder, postorder
        # Close the file when you're done.
        for line in file_ob:
            if ' ' in line:
                command, num = line.split()
                if command == "insert":
                    myBST.insert(num)
                if command == "delete":
                    myBST.deleteBook(num)
                #print command
                #print num
            else:
                line = line.split()
                myBST.traverse(line[0], myBST.getRoot())
                print ''
            if 'str' in line:
                break
    pass
Example #7
0
def main(argv):
    input_file = argv[1]

    # Instance of the binary search tree
    tree = BST()

    with open(input_file, 'r') as file_ob:
        for line in file_ob:
            line = line.split()

            if line[0] == 'insert':
                tree.insert(int(line[1]))

            if line[0] == 'delete':
                tree.delete(int(line[1]))

            if line[0] == 'preorder':
                tree.traverse('preorder', tree.getRoot())
                print("")

            if line[0] == 'inorder':
                tree.traverse('inorder', tree.getRoot())
                print("")

            if line[0] == 'postorder':
                tree.traverse('postorder', tree.getRoot())
                print("")

        # Close the file
        file_ob.close()
 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)
class TestBST(TestCase):
    def setUp(self):
        self.list1 = [3, 2, 1, 5, 6, 7]

        # Creating the BST1
        self.BST1 = BST(dtype=int, key=4)

        for val in self.list1:
            self.BST1 = self.BST1.insert(val)

    def test_insert(self):
        self.assertEqual(self.BST1.key, 4)
        self.assertEqual(self.BST1.left.key, 3)
        self.assertEqual(self.BST1.right.key, 5)

        self.BST1 = self.BST1.insert(9)
        self.assertEqual(self.BST1.right.right.right.right.key, 9)

    def test_preOrderTraversal(self):
        preOrderValues = [4, 3, 2, 1, 5, 6, 7]
        self.assertEqual(self.BST1.PreOT(),
                         ', '.join(str(i) for i in preOrderValues))

    def test_inOrderTraversal(self):
        inOrderValues = [1, 2, 3, 4, 5, 6, 7]
        self.assertEqual(self.BST1.IOT(),
                         ', '.join([str(i) for i in inOrderValues]))

    def test_postOrderTraversal(self):
        postOrderValues = [1, 2, 3, 7, 6, 5, 4]
        self.assertEqual(self.BST1.PostOT(),
                         ', '.join([str(i) for i in postOrderValues]))

    def tearDown(self):
        del self.list1
Example #10
0
class TranversalBST(object):
    def __init__(self):
        self.bst = BST(None)
        self.nodes = []
        
    def insert(self, value):
        if not self.bst.value:
            self.bst.value = value
        else:
            self.bst.insert(value)

    def contains(self, value):
        return bool(self.bst.find(value))

    def get(self, index):
        for i, value in enumerate(self.inorder()):
            if i == index:
                return value

    def inorder(self):
        current = self.bst  
        self.nodes = []
        stack = []
        while len(stack) > 0 or current is not None:
            if current is not None:
                stack.append(current)   
                current = current.left
            else:
                current = stack.pop()
                self.nodes.append(current.value)
                current = current.right
        return self.nodes


    def preorder(self):
        self.nodes = []
        stack = [self.bst]  
        while len(stack) > 0:
            curr = stack.pop()
            if curr is not None:
                self.nodes.append(curr.value)
                stack.append(curr.right)
                stack.append(curr.left)
        return self.nodes


    def preorder2(self):
        self.nodes = []
        current = self.bst  
        stack = []
        while len(stack) > 0 or current is not None:
            if current is not None:
                self.nodes.append(current.value)
                stack.append(current)   
                current = current.left
            else:
                current = stack.pop()               
                current = current.right            
        return self.nodes
Example #11
0
    def test_search(self):
        bin = BST()
        for i in range(50):
            bin.insert(i)

        self.assertEqual(bin.find(8).val, 8)
        self.assertEqual(bin.find(49).val, 49)
        self.assertEqual(bin.find(60), None)
 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)
Example #13
0
def demo():

    B = Node(50)
    tree = BST()

    tree.insert(tree.root, Node(50))
    tree.insert(tree.root, Node(48))
    tree.insert(tree.root, Node(52))
    tree.print_BST(tree.root)
Example #14
0
    def test_inorder_traversal(self):
        bst = BST()
        listi = [x for x in range(50)]
        random.shuffle(listi)
        for j in listi:
            bst.insert(j)

        inorderTreeWalk(bst.root)
        self.assertEqual(len(listi), bst.size)
Example #15
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 #16
0
    def test_Search_Iter(self):
        bst = BST()
        listi = [x for x in range(50)]
        random.shuffle(listi)
        for j in listi:
            bst.insert(j)

        node = treeSearch(bst.root, 32)
        self.assertIsNotNone(node)
        self.assertEqual(32, node.value)
Example #17
0
def heightrandom():
    for i in range(2, 10, 2):
        L = [100 * random() for x in range((2**i) - 1)]
        BSTTree = BST()
        TreapTree = Treap()
        for x in L:
            BSTTree.insert(x)
            TreapTree.insert(x)
        print("Complete Tree would have height of", i - 1)
        print("Height of BST is: ", BSTTree.height())
        print("Height of Treap is: ", TreapTree.height())
Example #18
0
 def test_Search(self):
     bst = BST()
     listi = [x for x in range(50)]
     random.shuffle(listi)
     for j in listi:
         bst.insert(j)
     searchValue = 40
     inorderTreeWalk(bst.root)
     node = treeSearch(bst.root, searchValue)
     self.assertIsNotNone(node)
     self.assertEqual(searchValue, node.value)
Example #19
0
 def test_MinMax_Recursive(self):
     bst = BST()
     listi = [x for x in range(50)]
     random.shuffle(listi)
     for j in listi:
         bst.insert(j)
     node = treeMinRecursive(bst.root)
     node2 = treeMaxRecursive(bst.root)
     self.assertIsNotNone(node)
     self.assertEqual(0, node.value)
     self.assertIsNotNone(node2)
     self.assertEqual(49, node2.value)
Example #20
0
    def test_delete_w_one_child(self):
        bin = BST()
        bin.insert(5)
        bin.insert(2)
        bin.insert(18)
        bin.insert(-4)
        bin.insert(3)
        bin.insert(21)
        bin.insert(19)
        bin.insert(25)

        bin.delete(bin.root.right)

        self.assertEqual([x.val for x in bin.get_level(1)], [2, 21])
Example #21
0
class SymbolTable:
    def __init__(self):
        self.bst = BST()
        self.pos = 0

    def add(self, identifier):
        param = [self.pos, str(identifier)]
        self.bst.insert(param)
        self.pos = self.pos + 1

    def search(self, identifier):
        return self.bst.search(str(identifier))

    def print(self):
        self.bst.print()
 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(
     )
Example #23
0
    def test_delete_w_two_children(self):
        bin = BST()
        bin.insert(5)
        bin.insert(2)
        bin.insert(12)
        bin.insert(-4)
        bin.insert(3)
        bin.insert(9)
        bin.insert(21)
        bin.insert(19)
        bin.insert(25)

        bin.delete(bin.root.right)

        self.assertEqual([x.val for x in bin.get_level(1)], [2, 19])
        self.assertEqual([x.val for x in bin.get_level(3)], [25])
Example #24
0
class SymbolTable:
    def __init__(self):
        self.tree = BST()

    def add(self, symbol):
        return self.tree.insert(symbol)

    def print(self):
        return self.tree.print()
Example #25
0
def main(argv):

    tree = BST(
    )  # Creating the instance of a binary search tree, and going to be
    # referring to it as tree.

    input_file = argv[
        1]  # This will be the input file with the tree instructions
    # passed in as an argument when the program is compiled.

    with open(input_file, 'r') as file_object:

        # Looping over the input file (file is passed in as argv[1])
        for line in file_object:
            # splitting each line into a task and a number, so this would mean that
            # the task will be refered to as line[0] and then the actual number
            # is going to be referred to as line[1] after the split.
            line = line.rstrip('\n')
            line = line.split()

            if line[0] == "insert":
                # calling the insert function.
                tree.insert((line[1]))

            if line[0] == "inorder":
                # for the tree traversals, these will only call the traverse function
                # which will then decide which traversal to execute.
                tree.traverse(line[0], tree.getRoot())
                print "\n",

            if line[0] == "preorder":
                tree.traverse(line[0], tree.getRoot())
                print "\n",

            if line[0] == "postorder":
                tree.traverse(line[0], tree.getRoot())
                print "\n",

            if line[0] == "delete":
                tree.delete(line[1])

    file_object.close()  # closing the input file after we finish reading it.
 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 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))
 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))
Example #29
0
class SymbolTable:
    def __init__(self):
        self.bst = BST()
        self.pos = 0

    def add(self, identifier):
        param = [self.pos, str(identifier)]
        self.bst.insert(param)
        self.pos = self.pos + 1

    def search(self, identifier):
        return self.bst.search(str(identifier))

    def get_identifier_id(self, id):
        id = self.search(id)
        if id is None:
            return -1
        return id[0]

    def print(self):
        self.bst.print()
Example #30
0
def main(argv):
	# Loop over input file (filename passed via argv).
	# Split each line into a task and number (if one exists) 
	#   hint: use the split method for strings https://docs.python.org/2/library/string.html#string.split
	# Perform the function corresponding to the specified task
	# i.e., insert, delete, inorder, preorder, postorder
	# Close the file when you're done.
	filename = argv[1]
	file = open(filename, "r")

	bst = BST()

	for line in file:
		line = line.strip('\n')
		task = line.split(" ")

		# If task is insert
		if (task[0] == "insert"):
			val = int(task[1])
			bst.insert(val)

		# If task is delete
		elif (task[0] == "delete"):
			val = int(task[1])
			bst.delete(val)

		# If task is inorder
		elif (task[0] == "inorder"):
			bst.traverse(task[0], bst.getRoot()) 

		# If task is preorder
		elif (task[0] == "preorder"):
			bst.traverse(task[0], bst.getRoot())

		# If task is postorder
		elif (task[0] == "postorder"):
			bst.traverse(task[0], bst.getRoot())

	# Close file
	file.close()
Example #31
0
class Window(object):
    def silentremove(self, filename):
        try:
            os.remove(filename)
        except OSError as e:  # this would be "except OSError, e:" before Python 2.6
            if e.errno != errno.ENOENT:  # errno.ENOENT = no such file or directory
                raise

    def __init__(self, master):
        self.silentremove("tree.png")
        self.silentremove("tree")
        self.tree = BST()
        self.display = None
        self.img = tkinter.Label(master)
        self.btn_add = tkinter.Button(master, text="add")
        self.btn_del = tkinter.Button(master, text="del")
        self.entry_node = tkinter.Entry(master)
        self.btn_add.bind("<Button-1>", self.add_element)
        self.btn_del.bind("<Button-1>", self.del_element)
        self.btn_add.pack(side="bottom")
        self.btn_del.pack(side="bottom")
        self.entry_node.pack(side="bottom")
        self.img.pack(fill="both")

    def del_element(self, event):
        self.tree.delete(int(self.entry_node.get()))
        self.tree.draw().render("tree")
        self.display = ImageTk.PhotoImage(image=Image.open("tree.png"))
        self.img.pack_forget()
        self.img = tkinter.Label(image=self.display)
        self.img.pack()

    def add_element(self, event):
        self.tree.insert(int(self.entry_node.get()))
        self.tree.draw().render("tree")
        self.display = ImageTk.PhotoImage(image=Image.open("tree.png"))
        self.img.pack_forget()
        self.img = tkinter.Label(image=self.display)
        self.img.pack()
Example #32
0
def main(argv):
    # Loop over input file (filename passed via argv).
    # Split each line into a task and number (if one exists)
    #   hint: use the split method for strings https://docs.python.org/2/library/string.html#string.split
    # Perform the function corresponding to the specified task
    # i.e., insert, delete, inorder, preorder, postorder
    # Close the file when you're done.
    file = argv[1]
    tasklist = []
    tree = BST()
    with open(file, 'r') as file_ob:
        for line in file_ob:
            tasks = line.strip()  #strips whitespace
            calls = tasks.split(
                " ")  #separates commands (some require 2 arguments)
            tasklist.append(calls)

        for task in tasklist:
            #these types of commands are the traversals inorder, preorder, postorder
            if task[0] == "inorder":
                tree.traverse("inorder", tree.getRoot())
                print("")  # just to make my output a little more readable
            elif task[0] == "preorder":
                tree.traverse("preorder", tree.getRoot())
                print("")  # just to make my output a little more readable
            elif task[0] == "postorder":
                tree.traverse("postorder", tree.getRoot())
                print("")  # just to make my output a little more readable
            elif len(task) == 2:
                command = task[0]  #here are the insert/delete commands
                value = int(task[1])
                if command == "insert":
                    tree.insert(value)
                elif command == "delete":
                    tree.delete(value)
                else:
                    print("this is not an appropriate BST method")
Example #33
0
 def insert_without_splay(self, z):
     BST.insert(self, z)
Example #34
0
 def insert(self, z):
     BST.insert(self, z)
     self.splay(z)
Example #35
0
from BST import BST

bst = BST(7, 'ok')
bst.insert(3, 'dooke')
bst.insert(10, 'poke')
bst.insert(5, 'poop')
bst.insert(1, 'dope')
bst.insert(8, 'lol')
bst.insert(9, 'haagu')
bst.insert(12,'paadu')
bst.printinorder()
print '\n'
'''try:
    print bst.getvalue(12)
    print bst.getvalue(9)
    print bst.getvalue(8)
    print bst.getvalue(1)
    print bst.getvalue(5)
    print bst.getvalue(10)
    print bst.getvalue(3)
    print bst.getvalue(7)
    print bst.getvalue(14)

except RuntimeError as e:
    print e'''

key = 19
if key in bst:
    print "I am in bst"
else:
    print 'No i am not'
class TranversalBST(object):
    def __init__(self):
        self.bst = BST(None)
        self.nodes = []
        
    def insert(self, value):
        if not self.bst.value:
            self.bst.value = value
        else:
            self.bst.insert(value)

    def contains(self, value):
        return bool(self.bst.find(value))

    def get(self, index):
        for i, value in enumerate(self.inorder()):
            if i == index:
                return value

    def inorder(self):
        current = self.bst  
        self.nodes = []
        stack = []
        while len(stack) > 0 or current is not None:
            if current is not None:
                stack.append(current)   
                current = current.left
            else:
                current = stack.pop()
                self.nodes.append(current.value)
                current = current.right
        return self.nodes


    def preorder(self):
        self.nodes = []
        stack = [self.bst]  
        while len(stack) > 0:
            curr = stack.pop()
            if curr is not None:
                self.nodes.append(curr.value)
                stack.append(curr.right)
                stack.append(curr.left)
        return self.nodes


    def preorder2(self):
        self.nodes = []
        current = self.bst  
        stack = []
        while len(stack) > 0 or current is not None:
            if current is not None:
                self.nodes.append(current.value)
                stack.append(current)   
                current = current.left
            else:
                current = stack.pop()               
                current = current.right            
        return self.nodes



    def preorder3(self):
        self.nodes = []
        node = self.bst
        if not node: return None
        stack = []  
        stack.append(node)  
        while stack:
            node = stack.pop()
            self.nodes.append(node.value)
            if node.right: stack.append(node.right) # RIGHT FIRST!
            if node.left: stack.append(node.left)
        return self.nodes



    
    def BFT(self):
        self.nodes = []
        node = self.bst
        if not node: return None
        queue = deque() 
        queue.append(node)  
        while queue:
            node = queue.popleft()
            self.nodes.append(node.value)
            if node.left: queue.append(node.left) # LEFT FIRST!
            if node.right: queue.append(node.right)

        return self.nodes
Example #37
0
__author__ = 'Hazem Safwat'
from BST import BST
import random
from tabulate import tabulate
table = [[]]
for i in range(51):  #creating 50 different trees
    size = random.randint(50,100)
    items = random.sample(range(1,12000) , size) #random items in tree has a size = size
    tree = BST(items[0])   #Root of the tree
    for j in range(1,size):    #inserting items in the tree
        tree.insert(items[j])
    counter = BST.stepCounter(tree)
    table.append([i , size , counter , 2*counter])

print(tabulate(table[1:51] , headers= ["no." , "number of items" ,"number of calls" ,"number of steps"  ]))
Example #38
0
class Test:
    __a=0
    def __init__(self):
       self.b=0
       self.__a=self.__a+1
       #Test.__a=Test.__a+1
    def get_a(self):
        return self.__a
test1=Test()
test2=Test()
print 'test1'
print 'a:%d'%(test1.get_a())
test1.a=10
print 'test2'
print 'a:%d'%(test1.a)

from BST import BST
import random

bst=BST()
bst.insert(int(random.random()*100))
bst.insert(int(random.random()*100))
bst.insert(int(random.random()*100))
bst.insert(int(random.random()*100))
bst.insert(int(random.random()*100))
bst.insert(int(random.random()*100))
bst.insert(int(random.random()*100))
bst.insert(int(random.random()*100))
bst.mid_travel()
Example #39
0
#!/usr/env/bin python3

# File that uses BST
from BST import BST

bst = BST(25)
bst.insert(12)
bst.insert(50)
bst.insert(6)
bst.insert(45)
bst.insert(1)

print("Does tree contain 1 {0}".format(bst.contains(1)))
print("Does tree contain 5 {0}".format(bst.contains(5)))
print("Does tree contain 12 {0}".format(bst.contains(12)))
print("Does tree contain 51 {0}".format(bst.contains(51)))