Example #1
0
def create_chain_bst(n):
    curr = 1
    mytree = BinarySearchTree()
    while curr <= n:  #For q1, h = n
        mytree.insert(curr)  #insert runtine is O(h)
        curr += 1
    return mytree
    def test_is_bst(self):
        node1 = b.Node(1)
        node2 = b.Node(2)
        node3 = b.Node(3)
        node4 = b.Node(4)
        node5 = b.Node(5)

        # not a bst
        node1.left = node2
        node1.right = node4
        node4.left = node3
        node4.right = node5
        self.class_under_test.root = node1

        self.assertFalse(b.is_bst(self.class_under_test))

        # is a bst
        node1 = b.Node(1)
        node2 = b.Node(2)
        node3 = b.Node(3)
        node4 = b.Node(4)
        node5 = b.Node(5)

        node2.left = node1
        node2.right = node4
        node4.left = node3
        node4.right = node5
        self.class_under_test.root = node2

        self.assertTrue(b.is_bst(self.class_under_test))
Example #3
0
    def setUp(self):
        # The testing tree should look like this:
        #               30s
        #          /         \
        #         /           \
        #        /             \
        #      10               43
        #     /  \           /      \
        #         21       34        45
        #        /  \     /  \       / \
        #      15             40        46
        #
        # All nodes should have a count == 1
        # except for 46 with count == 4

        self.empty_tree = bst.BinarySearchTree()
        self.tree = bst.BinarySearchTree()
        self.tree.insert(30)
        self.tree.insert(43)
        self.tree.insert(10)
        self.tree.insert(34)
        self.tree.insert(21)
        self.tree.insert(40)
        self.tree.insert(15)
        self.tree.insert(45)
        self.tree.insert(44)
        self.tree.insert(46)
        self.tree.insert(46)
        self.tree.insert(46)
        self.tree.insert(46)
Example #4
0
    def testInsert(self):
        tree = BinarySearchTree([])
        tree.insert(0)
        tree.insert(-5)
        tree.insert(-2)
        tree.insert(5)
        tree.insert(10)

        self.assertEquals(tree.root.parent, None)
        self.assertEquals(tree.root.key, 0)

        leftChild = tree.root.leftChild
        self.assertEquals(leftChild.parent, tree.root)
        self.assertEquals(leftChild.key, -5)

        leftRightChild = leftChild.rightChild
        self.assertEquals(leftRightChild.parent, leftChild)
        self.assertEquals(leftRightChild.key, -2)

        rightChild = tree.root.rightChild
        self.assertEquals(rightChild.parent, tree.root)
        self.assertEquals(rightChild.key, 5)

        rightRightChild = rightChild.rightChild
        self.assertEquals(rightRightChild.parent, rightChild)
        self.assertEquals(rightRightChild.key, 10)
    def testInsert(self):
        tree = BinarySearchTree([])
        tree.insert(0)
        tree.insert(-5)
        tree.insert(-2)
        tree.insert(5)
        tree.insert(10)

        self.assertEquals(tree.root.parent, None)
        self.assertEquals(tree.root.key, 0)

        leftChild = tree.root.leftChild
        self.assertEquals(leftChild.parent, tree.root)
        self.assertEquals(leftChild.key, -5)

        leftRightChild = leftChild.rightChild
        self.assertEquals(leftRightChild.parent, leftChild)
        self.assertEquals(leftRightChild.key, -2)

        rightChild = tree.root.rightChild
        self.assertEquals(rightChild.parent, tree.root)
        self.assertEquals(rightChild.key, 5)

        rightRightChild = rightChild.rightChild
        self.assertEquals(rightRightChild.parent, rightChild)
        self.assertEquals(rightRightChild.key, 10)
  def construct(entries):

    tree = BinarySearchTree()

    for entry in entries:

      key, value = entry

      tree.insert(key, value)

    return tree
Example #7
0
 def setUp(self):
     self.binaryTree = BinarySearchTree()
     self.binaryTree.addValue(8)
     self.binaryTree.addValue(3)
     self.binaryTree.addValue(10)
     self.binaryTree.addValue(6)
     self.binaryTree.addValue(1)
     self.binaryTree.addValue(4)
     self.binaryTree.addValue(14)
     self.binaryTree.addValue(7)
     self.binaryTree.addValue(13)
 def immutable_remove_leftmost(self):
     """ Returns a tree with the leftmost child removed.
         Search trees are treated as immutable objects in this method.
         This method is private. """
     if self.is_empty:
         return self
     elif self.left.is_empty:
         return self.right
     else:
         root = BinarySearchTree(self.key_map, BinaryTree(self.tree.data))
         root.left = self.left.immutable_remove_leftmost()
         root.tree.right = self.tree.right
         return root
Example #9
0
    def testSearch(self):
        tree = BinarySearchTree([0, -5, -2, 5, 10])

        self.assertEquals(tree.search(99), None)

        node = tree.search(-2)
        self.assertEquals(node.parent.key, -5)
        self.assertEquals(node.leftChild, None)
        self.assertEquals(node.rightChild, None)

        node = tree.search(10)
        self.assertEquals(node.parent.key, 5)
        self.assertEquals(node.leftChild, None)
        self.assertEquals(node.rightChild, None)
Example #10
0
    def test_post_order_traversal(self):
        data = ['S', 'E', 'X', 'A', 'R', 'C', 'H', 'M']
        tree = BinarySearchTree(TreeNode(data[0]))
        [tree.insert(TreeNode(i)) for i in data[1:]]
        expected = ['C', 'A', 'M', 'H', 'R', 'E', 'X', 'S']
        self.assertEqual(tree.postOrderTraverse(), expected)
        self.assertEqual(tree.postOrderTraverseInLoop(), expected)

        data = ['H', 'C', 'S', 'A', 'E', 'R', 'X']
        expected = ['A', 'E', 'C', 'R', 'X', 'S', 'H']
        tree = BinarySearchTree(TreeNode(data[0]))
        [tree.insert(TreeNode(i)) for i in data[1:]]
        self.assertEqual(tree.postOrderTraverse(), expected)
        self.assertEqual(tree.postOrderTraverseInLoop(), expected)
    def testSearch(self):
        tree = BinarySearchTree([0, -5, -2, 5, 10])

        self.assertEquals(tree.search(99), None)

        node = tree.search(-2)
        self.assertEquals(node.parent.key, -5)
        self.assertEquals(node.leftChild, None)
        self.assertEquals(node.rightChild, None)

        node = tree.search(10)
        self.assertEquals(node.parent.key, 5)
        self.assertEquals(node.leftChild, None)
        self.assertEquals(node.rightChild, None)
Example #12
0
def menu_bt():
    bt = BinarySearchTree.BinarySearchTree()
    blist = ArrayList.ArrayList()
    option = ""
    while option != '0':
        print("""
             1 Add to Binary Tree
             2 Remove from Binary Tree
             3 Display values using BF traversal
             4 Display values using in-order
             5 Display values using pre-order
             6 Display values using post-order
             7 Print height of tree
             0 Return to main menu
             """)
        option = input()
        if option == "1":
            bt.add(input("Enter the string index: "),input("Enter the value: "))
        elif option == "2":
            bt.remove(input("Enter index to be removed: "))
        elif option == "3":
            print(bt.bf_traverse())
        elif option == "4":
            print( bt.in_order(bt.r, []) )
        elif option == "5":
            print( bt.pre_order(bt.r, []) )
        elif option == "6":
           print( bt.post_order(bt.r, []) )
        elif option == "7":
            print(bt.height())
Example #13
0
    def __init_goto_list(self):
        newstate = 0

        def enter(word):
            assert type(word) == str, "word must be a string"
            nonlocal newstate
            state = 0
            j = 0

            # check if a prefix of word exists
            tmp = self.goto_list[state].findval(word[j])
            while j < len(word) and self.goto_list[state].findval(
                    word[j]) != -1:
                state = self.goto_list[state].findval(word[j])[1]
                j = j + 1
            # create states for all alphabets, that are not presented in the automata
            if j < len(word):
                for p in range(j, len(word)):
                    newstate += 1
                    self.goto_list[state].insert(word[p], newstate)
                    self.goto_list.append(BinarySearchTree.Node(word[p]))
                    self.output_list.append(None)
                    state = newstate
            # initialize output function for the inserted word
            self.output_list[state] = LinkedList.LinkedList(word)

        self.goto_list.append(BinarySearchTree.Node(chr(0)))
        self.output_list.append(None)
        for i in range(len(self.keywords)):
            enter(self.keywords[i])
Example #14
0
 def __init__(self):
     self.bookCatalog = ArrayList.ArrayList()
     self.shoppingCart = ArrayQueue.ArrayQueue()
     self.indexKey = ChainedHashTable.ChainedHashTable()
     self.indexSortedPrefix = BinarySearchTree.BinarySearchTree()
     self.bookSortedCatalog = ArrayList.ArrayList()
     self.similaGraph = AdjacencyList.AdjacencyList(0)
Example #15
0
 def test_remove_root_from_single_node_tree(self):
     remove_test_tree = bst.BinarySearchTree()
     remove_test_tree.insert(40)
     remove_test_tree.remove(40)
     root = remove_test_tree.get_root()
     self.assertIsNone(root);
     self.assertEqual(remove_test_tree.size(), 0)
Example #16
0
 def test_remove_node_not_in_tree(self):
     remove_test_tree = bst.BinarySearchTree();
     remove_test_tree.insert(20)
     remove_test_tree.insert(46)
     remove_test_tree.insert(16)
     remove_test_tree.remove(17)
     self.assertEqual(remove_test_tree.size(), 3)
Example #17
0
def make_binary_tree(numbers=None):
    if not numbers:
        numbers = [5, 2, 7, 1, 3, 6, 8, 0, 9, 4]
    tree = BinarySearchTree.BinarySearchTree()
    for i in numbers:
        tree.insert(i)
    return tree
 def test_to_sorted_doubly_linked_list(self):
     self.class_under_test.insert(1)
     self.class_under_test.insert(3)
     self.class_under_test.insert(4)
     self.class_under_test.insert(2)
     result = b.to_sorted_doubly_linked_list(self.class_under_test)
     self.assertTrue(result.head.data == 1)
     self.assertTrue(result.head.prev.data == 4)
Example #19
0
 def test_remove_duplicate_node_in_tree(self):
     remove_test_tree = bst.BinarySearchTree()
     remove_test_tree.insert(40)
     remove_test_tree.insert(46)
     remove_test_tree.insert(46)
     remove_test_tree.remove(46)
     self.assertEqual(remove_test_tree.find(46).count, 1)
     self.assertEqual(remove_test_tree.size(), 2)
Example #20
0
 def test_rotate_roots_left_child_to_right(self):
     self.bst = BinarySearchTree.BinarySearchTree()
     self.bst.insert(2)
     self.bst.insert(1)
     node1 = self.bst.get_node(1)
     node2 = self.bst.get_node(2)
     self.bst.rotate(node1)
     self.assertTrue(self.bst.root == node1 and node1.right == node2)
Example #21
0
 def test_remove_node_with_no_children(self):
     remove_test_tree = bst.BinarySearchTree();
     remove_test_tree.insert(20)
     remove_test_tree.insert(46)
     remove_test_tree.insert(16)
     remove_test_tree.remove(16)
     self.assertEqual(remove_test_tree.size(), 2)
     self.assertIsNone(remove_test_tree.find(16))
Example #22
0
    def test_prev_order_traversal(self):
        data = ['S', 'E', 'X', 'A', 'R', 'C', 'H', 'M']
        tree = BinarySearchTree(TreeNode(data[0]))
        [tree.insert(TreeNode(i)) for i in data[1:]]
        # map returns a iterator in Python3 instead of a list in Python2.
        # for i in a:
        #     print(i)
        expected = ['S', 'E', 'A', 'C', 'R', 'H', 'M', 'X']
        self.assertEqual(tree.prevOrderTraverse(), expected)
        self.assertEqual(tree.prevOrderTraverseInLoop(), expected)

        data = ['H', 'C', 'S', 'A', 'E', 'R', 'X']
        expected = ['H', 'C', 'A', 'E', 'S', 'R', 'X']
        tree = BinarySearchTree(TreeNode(data[0]))
        [tree.insert(TreeNode(i)) for i in data[1:]]
        self.assertEqual(tree.prevOrderTraverse(), expected)
        self.assertEqual(tree.prevOrderTraverseInLoop(), expected)
Example #23
0
 def test_remove_node_with_right_child(self):
     remove_test_tree = bst.BinarySearchTree();
     remove_test_tree.insert(20)
     remove_test_tree.insert(46)
     remove_test_tree.insert(16)
     remove_test_tree.insert(17)
     remove_test_tree.remove(16)
     self.assertEqual(remove_test_tree.size(), 3)
     self.assertIsNone(remove_test_tree.find(16))
     self.assertEqual(remove_test_tree.find(20).left.value, 17)
Example #24
0
 def getTopTenPrice(self):
     print("--------------------------------------------------")
     print("-----------Top ten assets for price($):-----------")
     a = BinarySearchTree.DSABinarySearchTree()
     for i in range(self.vertices.getLength()):
         a.insert(
             self.vertices.getNthNode(i).price,
             self.vertices.getNthNode(i).label)
     for i in range(10):
         a.max()
     print("-----------Top ten assets for price($):-----------")
Example #25
0
 def getTopTenGain(self):
     print("------Top ten gainers in the last 7 days(%):------")
     c = BinarySearchTree.DSABinarySearchTree()
     for i in range(self.vertices.getLength()):
         c.insert(
             self.vertices.getNthNode(i).sevenDay,
             self.vertices.getNthNode(i).label)
     for i in range(10):
         c.max()
     print("------Top ten gainers in the last 7 days(%):------")
     print("--------------------------------------------------")
Example #26
0
 def getTopTenVolume(self):
     print("--------------------------------------------------")
     print("----Top ten assets for volume in last 24hr($):----")
     b = BinarySearchTree.DSABinarySearchTree()
     for i in range(self.vertices.getLength()):
         b.insert(
             self.vertices.getNthNode(i).volume,
             self.vertices.getNthNode(i).label)
     for i in range(10):
         b.max()
     print("----Top ten assets for volume in last 24hr($):----")
     print("--------------------------------------------------")
Example #27
0
 def test_rotate_node_with_only_left_child(self):
     self.bst = BinarySearchTree.BinarySearchTree()
     for i in range(3, -1, -1):
         self.bst.insert(i)
     nodes = [self.bst.get_node(x) for x in range(4)]
     self.bst.rotate(nodes[1])
     self.assertTrue(nodes[3].left == nodes[1]
                     and nodes[1].parent == nodes[3]
                     and nodes[1].left == nodes[0]
                     and nodes[0].parent == nodes[1]
                     and nodes[1].right == nodes[2]
                     and nodes[2].parent == nodes[1])
 def immutable_remove(self, Key):
     """ Returns a tree where one occurrence of an item with the provided key has been removed.
         Search trees are treated as immutable objects in this method.
         This method is private. """
     if self.is_empty:
         return self
     ownKey = self.key
     if Key > ownKey:
         root = BinarySearchTree(self.key_map, BinaryTree(self.tree.data))
         root.tree.left = self.tree.left
         root.right = self.right.immutable_remove(Key)
         return root
     elif Key < ownKey:
         root = BinarySearchTree(self.key_map, BinaryTree(self.tree.data))
         root.left = self.left.immutable_remove(Key)
         root.tree.right = self.tree.right
         return root
     elif (not self.left.is_empty) and (not self.right.is_empty):
         root = BinarySearchTree(self.key_map, BinaryTree(self.right.get_leftmost().tree.data))
         root.tree.left = self.tree.left
         root.right = self.right.immutable_remove_leftmost()
         return root
     elif self.left.is_empty:
         return self.right
     else:
         return self.left
Example #29
0
 def test_get_length_of_a_binary_tree(self):
     tree = BinarySearchTree(TreeNode(0))
     self.assertEqual(len(tree), 1)
     tree.insert(TreeNode(1))
     tree.insert(TreeNode(2))
     tree.insert(TreeNode(3))
     self.assertEqual(len(tree), 4)
Example #30
0
 def insert(self, key, value):
     entry = BST.BSTNode(key, value)
     if not self.root:
         self.root = entry
     x = self.insertOps(entry, self.root)
     try:
         print("x key : ", x.key, ", x dad key : ", x.parent.key)
     except AttributeError:
         print("root key : ", x.key)
     while x != self.root:
         self.splay(x)
         self.inOrder()
     return x
Example #31
0
def main():
    NUMTESTS = 3
    test = [False] * NUMTESTS
    p = None

    try:
        p = BinarySearchTree.DSABinarySearchTree()
        print('\033[92m' "BST successfully created!" '\033[0m')
        test[0] = True
    except:
        print("Failed")

    try:
        p.insert("Alex", 5)
        p.insert("Daniel", 8)
        p.insert("Geoff", 4)
        p.insert("Fred", 6)
        p.insert("George", 9)
        print('\033[92m' "Data successfully inserted!" '\033[0m')
        test[1] = True
    except:
        print("Failed")

    try:
        old_stdout = sys.stdout
        new_stdout = io.StringIO()
        sys.stdout = new_stdout
        p.max()
        val = new_stdout.getvalue()
        sys.stdout = old_stdout
        if val == "9 = George":
            print("Error")
        print('\033[92m' "Max successfully found!" '\033[0m')
        test[2] = True
    except:
        print("Failed")

    count = 0
    for i in range(NUMTESTS):
        if test[i] == True:
            print("Test", i, "passed!")
            count += 1
    print('\033[93m'
          "Result for binarySearchTree.py =", (count / NUMTESTS) * 100, "%"
          '\033[0m')
Example #32
0
def create_complete_bst(n):
    def add_items(bst, low, high):
        #recursive
        if low >= (
                high + 1
        ) // 2:  ##insert n number of nodes, and each time you insert, it takes h = log(n)
            bst.insert(low)  ##time because it is a complete bst
        else:
            bst = add_items(bst, low * 2, high)
            now = low
            times = ((high + 1) // 2) // low
            for i in range(times):
                bst.insert(now)
                now += low * 2
        return bst

    bst = BinarySearchTree()
    add_items(bst, 1, n)
    return bst
Example #33
0
    def test_binarytree(self):
        points = 0.5
        q = BinarySearchTree.BinarySearchTree()
        try:
            self.assertIsNone(q.find(2))
            self.assertAlmostEqual(q.remove(2), False)
        except:
            pass
        finally:
            points += 0.5

        try:
            q.add(3, "third")
            q.add(2, "second")
            q.add(1, "first")
            self.assertAlmostEqual(q.size(), 3)
            self.assertAlmostEqual(q.find(2.5), "third")
            q.remove(3)
            self.assertIsNone(q.find(3))
            self.assertAlmostEqual(q.size(), 2)
            q.add(3, "third")
            q.add(5, "fifth")
            q.add(4, "fourth")

            self.assertAlmostEqual(q.size(), 5)
            self.assertAlmostEqual(q.find(3.4), "fourth")
            print("In order")
            q.in_order()
            print("Pre oder")
            q.pre_order()
            print("Pos order")
            q.pos_order()
            print("BF Traversal")
            q.bf_traverse()
            self.assertAlmostEqual(q.height(), 4)
            points += 1
        except:
            print("BinarySearchTreeTest is not correct")
        finally:

            print(f"BinarySearchTreeTest: {points} Points")
Example #34
0
def main():
    inputFile = 'Test0.txt'
    outputFile = 'Test0_output.txt'

    tree = BinaryTree.BinaryTree(inputFile)
    bst = BinarySearchTree.BinarySearchTree()

    # Binary Tree tests
    with open(outputFile, 'w') as f:
        f.write(' '.join(
            str(x) for x in tree.inOrderTraversal(tree.getRoot())))
        f.write('\n')
        tree.clearTraversalResult()

        f.write(' '.join(
            str(x) for x in tree.preOrderTraversal(tree.getRoot())))
        f.write('\n')
        tree.clearTraversalResult()

        f.write(' '.join(
            str(x) for x in tree.postOrderTraversal(tree.getRoot())))
        f.write('\n')
        tree.clearTraversalResult()

    print(tree.isBST(tree.getRoot()))

    # Binary Search Tree tests
    root = bst.getRoot()
    root.addKey(random.randint(1, 1000000))

    for x in random.sample(range(2, 10000000), 1000000):
        bst.addNode(root, x)

    print(bst.isBST(bst.getRoot()))

    sys.exit()
    def test_find_largest_bst(self):
        node, size = b.find_largest_bst(self.class_under_test)
        self.assertTrue(node == None)
        self.assertTrue(size == 0)

        # whole tree is a bst
        #          2 <- bst!
        #        1   4
        #          3   5
        node1 = b.Node(1)
        node2 = b.Node(2)
        node3 = b.Node(3)
        node4 = b.Node(4)
        node5 = b.Node(5)

        node2.left = node1
        node2.right = node4
        node4.left = node3
        node4.right = node5
        self.class_under_test.root = node2

        node, size = b.find_largest_bst(self.class_under_test)
        self.assertTrue(node.data == 2)
        self.assertTrue(size == 5)

        # part of tree is a bst; there's only one bst
        #          2
        #        1   3
        #          6   5 <- bst!
        #            4   7
        #                  8
        node1 = b.Node(1)
        node2 = b.Node(2)
        node3 = b.Node(3)
        node4 = b.Node(4)
        node5 = b.Node(5)
        node6 = b.Node(6)
        node7 = b.Node(7)
        node8 = b.Node(8)

        node2.left = node1
        node2.right = node3
        node3.left = node6
        node3.right = node5
        node5.left = node4
        node5.right = node7
        node7.right = node8
        self.class_under_test.root = node2

        node, size = b.find_largest_bst(self.class_under_test)
        self.assertTrue(node.data == 5)
        self.assertTrue(size == 4)

        # part of tree is a bst; there's more than one bst
        #             2
        # bst! -> 1       3
        #       0  1.5  6   5 <- largest bst!
        #                 4   7
        #                       8
        node0 = b.Node(0)
        node1 = b.Node(1)
        node15 = b.Node(1.5)
        node2 = b.Node(2)
        node3 = b.Node(3)
        node4 = b.Node(4)
        node5 = b.Node(5)
        node6 = b.Node(6)
        node7 = b.Node(7)
        node8 = b.Node(8)

        node1.left = node0
        node1.right = node15
        node2.left = node1
        node2.right = node3
        node3.left = node6
        node3.right = node5
        node5.left = node4
        node5.right = node7
        node7.right = node8
        self.class_under_test.root = node2

        node, size = b.find_largest_bst(self.class_under_test)
        self.assertTrue(node.data == 5)
        self.assertTrue(size == 4)
Example #36
0
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

""" A very simple testing script for the BinarySearchTree class. """

from BinarySearchTree import *

import itertools
import random

t = BinarySearchTree()
print t
print

n = random.randint(5, 15)

for _ in itertools.repeat(None, n):
    x = random.randint(1, 100)
    print "Adding %d..." % x
    t.insert(x)

print
print "Tree of size %d:" % t.getSize()
print t

print 
Example #37
0
from BinarySearchTree import *
from Node import *
from Debugger import *
import sys


debug = Debugger()
debug.disable()

debug.printMsg("hello, joel")
bst = BinarySearchTree("Joel")


bst.insert("34", 34)
bst.insert("43", 43)
bst.insert("51", 51)
bst.insert("12", 12)
print "++" * 10

if "43" in bst:
	print "in here"

# print res.data
    r: current node
'''
def recover_bst_in_order(r):
    global prev, first, second
    if r:
        recover_bst_in_order(r.left)
        if not prev:
            prev = r
        else:
            if r.data < prev.data:
                if not first:
                    first = prev
                # if first is second's direct prior in in-order traversal, second is r
                # otherwise second will be overwritten later
                second = r
            prev = r    
        recover_bst_in_order(r.right)

def recover_bst(r):
    recover_bst_in_order(r)
    print first,second
    first.data, second.data = second.data, first.data
    return r

if __name__=='__main__':
    t=BinarySearchTree()
    data = [1,2,6,4,5,3,7,8]
    t.create_tree(data)    
    recover_bst(t.root)
    t.in_order_print(t.root)
 def testInOrderWalk(self):
     tree = BinarySearchTree([5, 1, 3, 9, -1, -2])
     self.assertEquals(tree.inOrderWalk(), [-2, -1, 1, 3, 5, 9])
Example #40
0
class Set:
    """Implementation of the set data structure.
    A Set here uses a 'BinarySearchTree' as the 
    internal data container.
    A Set is basically a data container that allows 
    no duplicates in it.

    @author Thomas Lang
    @version 1.0, 06/02/2015
    """

    def __init__(self):
        """Creates a new Set by instantiating the BinarySearchTree."""
        self.tree = BinarySearchTree()

    def isEmpty(self):
        """Checks if the Set has no elements in it.
        
        @return True if the set is empty, False otherwise. """
        return self.tree.isEmpty()

    def size(self):
        """Returns the total number of elements contained in the set.
        
        @return The size of the set. """
        return self.tree.getSize()

    def union(self, other):
        """Returns the union of this set and the passed other.
        The union of two sets describes all elements that are either
        stored in the first or the second one, or both.
        
        @return The union of the two sets. """

        if other is None:
            raise ValueError("Second set must not be null")

        unionedSet = Set()
        l = self.__getAll()
        l += other.__getAll()
        l.sort()
        unionedSet.addAll(l)
        return unionedSet

    def intersect(self, other):
        """Returns the intersection of this set and the passed other.
        The intersection of two sets describes all elements that are
        both stored in the first and the second one.
        
        @return The intersection of the two sets."""

        if other is None:
            raise ValueError("Second set must not be null")

        intersectedSet = Set()
        l = other.__getAll()

        for item in self.__getAll():
            if item in l:
                intersectedSet.add(item)

        return intersectedSet

    def difference(self, other):
        """Returns this set reduced by the passed other set.
        The difference between two sets A and B describes all
        elements, that are stored in A but not in B.
        
        @return The difference of this set by the passed other."""

        if other is None:
            raise ValueError("Second set must not be null")

        differenceSet = Set()
        l = other.__getAll()

        for item in self.__getAll():
            if not item in l:
                differenceSet.add(item)

        return differenceSet

    def __getAll(self):
        """Returns a list containing all elements in the set."""
        return self.tree.getAll()

    def add(self, value):
        """Adds the passed value to the set"""
        return self.tree.add(value)

    def addAll(self, collection):
        """Adds all elements from the passed collection to this set."""
        if collection is None:
            raise ValueError("Passed collection must not be null")

        for item in collection:
            self.add(item)

    def contains(self, element):
        """Checks if the passed element is contained in this set.
        
        @return True if the elements is in this set, False otherwise."""
        return self.tree.contains(element)

    def remove(self, element):
        """Deletes the passed element from this set."""
        return self.tree.delete(element)

    def isSubsetOf(self, other):
        """Checks if this set is a subset of the passed one.
        
        @return True if it is, False otherwise."""

        if other is None:
            raise ValueError("Second set must not be null")

        l = other.__getAll()
        isSubset = True

        for item in self.__getAll():
            if not item in l:
                isSubset = False
                break

        return isSubset

    def hasSubset(self, other):
        """Checks if the passed set is a subset of this one.
        
        @return True if it is, False otherwise."""

        if other is None:
            raise ValueError("Second set must not be null")

        lall = self.__getAll()
        hasSubset = True

        for item in other.__getAll():
            if not item in lall:
                hasSubset = False
                break

        return hasSubset

    def clear(self):
        """Removes all elements from this set."""
        self.tree = BinarySearchTree()

    def __str__(self):
        """Returns a String representation of this set."""
        if self.isEmpty():
            return "(empty set)"
        return self.tree.__str__()
Example #41
0
 def __init__(self):
     """Creates a new Set by instantiating the BinarySearchTree."""
     self.tree = BinarySearchTree()
Example #42
0
 def clear(self):
     """Removes all elements from this set."""
     self.tree = BinarySearchTree()
def InOrderTreeWalk(x):
	a = []
	if x != None:
		a += InOrderTreeWalk(x.left)
		a += [x.key]
		a += InOrderTreeWalk(x.right)
	return a
	
def TreeSort(A):
	T = BinarySearchTree()
	for i in range(0, len(A)):
		T.insert(A[i])
	return InOrderTreeWalk(T.root)

if __name__=="__main__":
	t = BinarySearchTree()
	print('empty: ' + str(t.isEmpty()))
	print('size: ' + str(t.size()))
	t.insert(11)
	t.insert(6)
	t.insert(19)
	t.insert(4)
	t.insert(8)
	t.insert(17)
	t.insert(43)
	t.insert(5)
	t.insert(10)
	t.insert(31)
	t.insert(49)
	print('')
	
def TreeSort(A):
	T = BinarySearchTree()
	for i in range(0, len(A)):
		T.insert(A[i])
	return InOrderTreeWalk(T.root)
Example #45
0
import BinarySearchTree as BST

bst = BST.BinarySeaarchTree()

a = """
1. Insert
2. Search
3. Delete
4. In-order
5. Pre-Order
6. Post-Order
7. Level-Order"""

while True:
    print(a)
    choice = int(input('Enter your choice: '))
    if choice ==1:
        dat = input('Enter the data you want to insert: ')
        bst.insert(dat)

    elif choice == 2:
        dat = input('Enter the element you want to search: ')
        if bst.search(dat):
            print(f'{dat} is in the tree')
        else:
            print(f'{dat} is not in the tree')
    elif choice == 3:
        dat = input('Enter the element to delete: ')
        bst.remove(dat)
    elif choice == 4:
        print('In-order traversal: ')
Example #46
0
def bst_main():
    T = create_list_consecutive_numbers(10000)
    array = get_input("2sumtest1.txt")
    bst = BST.BinarySearchTree(array)
    print(sum2_bst(bst, T, array))
    def testDelete(self):
        # Test the no left sub child case
        tree = BinarySearchTree([1, 2])
        tree.delete(tree.root)
        self.assertEquals(tree.root.key, 2)
        self.assertEquals(tree.root.leftChild, None)
        self.assertEquals(tree.root.rightChild, None)

        # Test the no right sub child case
        tree = BinarySearchTree([2, 1])
        tree.delete(tree.root)
        self.assertEquals(tree.root.key, 1)
        self.assertEquals(tree.root.leftChild, None)
        self.assertEquals(tree.root.rightChild, None)

        # Test the right sub tree successor is right child case
        tree = BinarySearchTree([1, 0, 2])
        tree.delete(tree.root)
        self.assertEquals(tree.root.key, 2)
        self.assertEquals(tree.root.leftChild.key, 0)
        self.assertEquals(tree.root.rightChild, None)

        # Test the right sub tree successor is not right child case
        tree = BinarySearchTree([0, -1, 3, 1])
        tree.delete(tree.root)
        self.assertEquals(tree.root.key, 1)
        self.assertEquals(tree.root.leftChild.key, -1)
        self.assertEquals(tree.root.rightChild.key, 3)
Example #48
0
        closest = current_node.data

    if value < current_node.data:
        return findclosestvalueinbsthelper(current_node.left, value, closest)

    else:
        return findclosestvalueinbsthelper(current_node.right, value, closest)

    return closest


def findclosestvalueinbst(tree: BinarySearchTree, value: int) -> int:
    return findclosestvalueinbsthelper(tree.head, value,
                                       abs(tree.head.data - value))


if __name__ == "__main__":

    tree = BinarySearchTree(10)
    tree.insert(5)
    tree.insert(15)
    tree.insert(2)
    tree.insert(5)
    tree.insert(13)
    tree.insert(22)
    tree.insert(1)
    tree.insert(14)

    value = 12
    print(findclosestvalueinbst(tree, value))
        result.append(root)
    cnt[0]+=1
    midOrder(root.right, k, result, cnt)
    
def kthSmallest(root, k):
    """
    :type root: TreeNode
    :type k: int
    :rtype: int
    """
    result = []
    midOrder(root, k, result,[1])
    return result[0].data

if __name__ == '__main__':
    t=BinarySearchTree()
    ''' The tree is :
                        20
                     /      \
                  10          40
                /    \       /  \
               3       17   35    73
              /  \     / \          \
             1    7  15  18         89
             \    /  /
              2  5  11
                / \   \
               4   6   12
    
    '''
    a=[20,10,40,3,17,35,73,1,7,15,18,89,2,5,11,4,6,12]