Esempio n. 1
0
class BinaryTreeTest(unittest.TestCase):
    def setUp(self):
        cathy = TreeNode('Cathy')
        cathy.left = TreeNode('Alex')
        cathy.right = TreeNode('Frank')

        sam = TreeNode('Sam')
        sam.left = TreeNode('Nancy')
        violet = TreeNode('Violet')
        violet.left = TreeNode('Tony')
        violet.right = TreeNode('Wendy')
        sam.right = violet

        les = TreeNode('Les')
        les.left = cathy
        les.right = sam

        self.tree = BinaryTree(les)

    def test_depthFirstPreOrderTraverse(self):
        self.assertEqual(self.tree.depthFirstPreOrderTraverse(),
                         'Les,Cathy,Alex,Frank,Sam,Nancy,Violet,Tony,Wendy')

    def test_depthFirstInOrderTraverse(self):
        self.assertEqual(self.tree.depthFirstInOrderTraverse(),
                         'Alex,Cathy,Frank,Les,Nancy,Sam,Tony,Violet,Wendy')

    def test_depthFirstPostOrderTraverse(self):
        self.assertEqual(self.tree.depthFirstPostOrderTraverse(),
                         'Alex,Frank,Cathy,Nancy,Tony,Wendy,Violet,Sam,Les')

    def test_breathFirst(self):
        self.assertEqual(self.tree.breathFirst(),
                         'Les,Cathy,Sam,Alex,Frank,Nancy,Violet,Tony,Wendy')
Esempio n. 2
0
def arrayBST(l, start, end):
    mid = (start + end) / 2
    if start <= end:
        tree = BinaryTree(l[mid])
        tree.left = arrayBST(l, start, mid - 1)
        tree.right = arrayBST(l, mid + 1, end)
        return tree
Esempio n. 3
0
def testTreeWithOneNode():
    print(divider + "Executing testTreeWithOneNode()...")
    tree = BinaryTree()
    tree.insert(Node(0))
    assert (tree.size == 1)
    assert (tree.height == 0)
    print("Passed" + divider)
Esempio n. 4
0
def arrayBST(l,start,end):
	mid=(start+end)/2
	if start<=end:
		tree=BinaryTree(l[mid])
		tree.left=arrayBST(l,start,mid-1)
		tree.right=arrayBST(l,mid+1,end)
		return tree
Esempio n. 5
0
def testSingleInserts(loops):
    print(divider + "Executing testSingleInserts()...")
    for i in range(loops):
        tree = BinaryTree()
        val = randint(MIN_INT_32, MAX_INT_32)
        tree.insert(Node(val))
        assert (tree.size == 1)
        assert (tree.height == 0)
    print("Passed" + divider)
Esempio n. 6
0
    def __init__(self, *args, **kwargs):
        #init method is inialized for each time that a test is run
        super(TestBinarySearchTree, self).__init__(*args, **kwargs)
        self.word = "hey"
        self.binaryTree = BinaryTree(self.word)
        self.words = [  "this", "is", "my", "exercise"]

        for word in self.words:
            self.binaryTree.insert_value(word)
Esempio n. 7
0
def testBFSSingleInsert():
    print(divider + "Executing testBFSSingleInsert()...")
    nodes = []
    tree = BinaryTree()
    tree.insert(Node(7))
    nodes = tree.getNodesBFS()
    print(nodesToString(nodes))
    assert (nodes[0].data == 7)
    print("Passed" + divider)
Esempio n. 8
0
def testSequentialInsert():
    print(divider + "Executing testSequentialInsert()...")
    tree = BinaryTree()
    for i in range(1, 11):
        tree.insert(Node(i))
    assert (tree.root.data == 1)
    assert (tree.size == 10)
    #print("Tree height is {}, expected to be {}".format(tree.height, 9))
    assert (tree.height == 9)
    print("Passed" + divider)
Esempio n. 9
0
class TestBinarySearchTree(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        #init method is inialized for each time that a test is run
        super(TestBinarySearchTree, self).__init__(*args, **kwargs)
        self.word = "hey"
        self.binaryTree = BinaryTree(self.word)
        self.words = [  "this", "is", "my", "exercise"]

        for word in self.words:
            self.binaryTree.insert_value(word)

    def test_search(self):
        x, path  = self.binaryTree.find_word("this")
        self.assertEqual(x, True)
        x, path  = self.binaryTree.find_word("not")
        self.assertEqual(x, False)

    def test_delete(self):
        self.binaryTree.delete_node("is")
        x, path  = self.binaryTree.find_word("is")
        self.assertFalse(x)

    def test_pre_order(self):
        print("Pre order Print")
        self.binaryTree.print_pre_order()
Esempio n. 10
0
def testBFSRandom():
    print(divider + "Executing testBFSRandom()...")
    tree = BinaryTree()
    expectedNodes = [32, 16, 50, 2, 30, 48, 53, 5, 18, 12]
    for num in randomNumbers:
        tree.insert(Node(num))
    bfsNodes = tree.getNodesBFS()
    print(nodesToString(bfsNodes))
    # Ensure that the order of the nodes is in the proper order for BFS
    for i in range(0, len(expectedNodes)):
        assert (bfsNodes[i].data == expectedNodes[i])
    print("Passed" + divider)
Esempio n. 11
0
def testDFSRandom():
    print(divider + "Executing testDFSRandom()...")
    tree = BinaryTree()
    expectedNodes = [32, 16, 2, 5, 12, 30, 18, 50, 48, 53]
    for number in randomNumbers:
        tree.insert(Node(number))
    assert (tree.size == len(randomNumbers))
    nodes = tree.getNodesDFS()
    print("Returned nodes = {}".format(nodesToString(nodes)))
    print("Expected nodes = {}".format([n for n in expectedNodes]))

    # Ensure that the order of the nodes is in the proper order for DFS
    for i in range(0, len(nodes)):
        assert (nodes[i].data == expectedNodes[i])
    print("Passed" + divider)
Esempio n. 12
0
def buildParseTree(fpexp):
    fpList = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree

    for i in fpList:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in ['and', 'or', 'not', ')']:  #added boolean operators
            currentTree.setRootVal(int(i))
            parent = pStack.pop()
            currentTree = parent
        elif i in ['and', 'or', 'not']:  #added boolean operators
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError

    return eTree
Esempio n. 13
0
def buildParseTree(fpexp):
 	fplist = fpexp.split()
 	pStack = Stack()
 	eTree = BinaryTree('')
 	pStack.push(eTree)
 	currentTree = eTree

 	for i in fplist:
 		if i == '(':
 			currentTree.insertLeft('')
 			pStack.push(currentTree)
 			currentTree = currentTree.getLeftChild()
 		elif i not in ['+', '-', '*', '/', ')']:
 			currentTree.setRootVal(int(i))
 			parent = pStack.pop()
 			currentTree = parent
 		elif i in ['+', '-', '*', '/']:
 			currentTree.setRootVal(i)
 			currentTree.insertRight('')
 			pStack.push(currentTree)
 			currentTree = currentTree.getRightChild()
 		elif i == ')':
 			currentTree = pStack.pop()
 		else:
 			raise ValueError
 	return eTree
Esempio n. 14
0
def build_parse_tree(fp_exp):
    fp_list = fp_exp.split()
    p_stack = Stack()
    e_tree = BinaryTree('')
    p_stack.push(e_tree)
    current_tree = e_tree
    for i in fp_list:
        if i == '(':
            current_tree.insert_left('')
            p_stack.push(current_tree)
            current_tree = current_tree.get_left_child()
        elif i not in ['+','-','*','/',')']:
            current_tree.set_root_val(int(i))
            parent = p_stack.pop()
            current_tree = parent
        elif i in ['+','-','*','/']:
            current_tree.set_root_val(i)
            current_tree.insert_right('')
            p_stack.push(current_tree)
            current_tree = current_tree.get_right_child()
        elif i == ')':
            current_tree = p_stack.pop()
        else:
            raise ValueError
    return e_tree
Esempio n. 15
0
def buildParseTree(the_exp):
    the_list = the_exp.split()
    p_stack = Stack()
    the_tree = BinaryTree('')
    p_stack.push(the_tree)
    current_tree = the_tree

    for i in the_list:
        if i == '(':
            current_tree.insertLeft('')
            p_stack.push(current_tree)
            current_tree = current_tree.getLeftChild()

        elif i not in ['+', '-', '*', '/', ')']:
            current_tree.setRootValue(int(i))
            current_tree = p_stack.pop()

        elif i in ['+', '-', '*', '/']:
            current_tree.setRootValue(i)
            current_tree.insertRight('')
            p_stack.push(current_tree)
            current_tree = current_tree.getRightChild()

        elif i == ')':
            current_tree = p_stack.pop()

        else:
            raise ValueError

    return the_tree
def in_pre(inorder, preorder, start, end):
    if start > end:
        return None

    tree = BinaryTree(preorder[in_pre.index])
    in_pre.index += 1

    if start == end:
        return tree

    i = inorder.index(tree.key)

    tree.left = in_pre(inorder, preorder, start, i - 1)
    tree.right = in_pre(inorder, preorder, i + 1, end)

    return tree
Esempio n. 17
0
def testEmptyTree():
    print(divider + "Executing testEmptyTree()...")
    tree = BinaryTree()
    assert (tree.size == 0)
    assert (tree.height == 0)
    assert (tree.root is None)
    print("Passed" + divider)
Esempio n. 18
0
def build_parse_tree(exp):
    tokens = exp
    # print(tokens)
    stack = Stack()
    tree = BinaryTree('?')
    stack.push(tree)
    currentTree = tree
    for t in tokens:
        # RULE 1: If token is '(' add a new node as left child
        # and descend into that node
        if t == '(':
            currentTree.insert_left('?')
            stack.push(currentTree)
            currentTree = currentTree.get_left_tree() 
        # RULE 2: If token is operator set key of current node
        # to that operator and add a new node as right child
        # and descend into that node
        elif t in ['+', '-', '*', '/', '**']:
            currentTree.set_key(t)
            currentTree.insert_right('?')
            stack.push(currentTree)
            currentTree = currentTree.get_right_tree()
        # RULE 3: If token is number, set key of the current node
        # to that number and return to parent
        elif t not in ['+', '-', '*', '/', '**', ')'] :
            currentTree.set_key(float(t))
            parent = stack.pop()
            currentTree = parent
        # RULE 4: If token is ')' go to parent of current node
        elif t == ')':
            currentTree = stack.pop()
        else:
            raise ValueError
    return tree
Esempio n. 19
0
 def sort(data_array, order="Desc"):
     heap_type = (order == "Desc" and "min") or "max"
     # 建立堆方式1 从最后一个节点父节点开始
     start_index = BinaryHeap.get_parent_index(len(data_array) - 1)
     for adjust_index in range(start_index, -1, -1):
         BinaryHeap.__move__down(heap_type, data_array, adjust_index)
     # 建立堆方式2 每个节点都向上调整
     # for i in range(len(input_data)):
     #     BinaryHeap.__move__up__(heap_type, input_data, i)
     bt = BinaryTree(data_array)
     node_text_map, edges = bt.get_show_info()
     GraphVisualization.show(node_text_map, edges, view_graph=True)
     # 依次与第i个元素交换 然后调整
     for i in range(len(data_array)-1, 0, -1):
         data_array[i], data_array[0] = data_array[0], data_array[i]
         BinaryHeap.__move__down(heap_type, data_array, 0, i)
     return data_array
Esempio n. 20
0
    def setUp(self):
        cathy = TreeNode('Cathy')
        cathy.left = TreeNode('Alex')
        cathy.right = TreeNode('Frank')

        sam = TreeNode('Sam')
        sam.left = TreeNode('Nancy')
        violet = TreeNode('Violet')
        violet.left = TreeNode('Tony')
        violet.right = TreeNode('Wendy')
        sam.right = violet

        les = TreeNode('Les')
        les.left = cathy
        les.right = sam

        self.tree = BinaryTree(les)
Esempio n. 21
0
def testRandomInsert():
    print(divider + "Executing testRandomInsert()...")
    numbers = [7, 2, 10, 4, 3, 1, 5, 8, 6, 9]
    tree = BinaryTree()
    for number in numbers:
        tree.insert(Node(number))
    assert (tree.root.data == 7)
    assert (tree.size == 10)
    print("Tree height is {}, expected to be {}".format(tree.height, 4))
    tree.printDFS()
    print()
    tree.printBFS()
    assert (tree.height == 4)
    print("Passed" + divider)
Esempio n. 22
0
	def tree(self):
		chars = list(set(self.text))
		occurs = {c: self.text.count(c)/len(self.text) for c in self.text}
		key = lambda i: occurs[i]
		chars = sorted(chars, key = key)
		nodes = [Node(label = c) for c in chars]

		while len(nodes) > 1:
			n1, n2 = nodes[0], nodes[1]
			del nodes[0]
			nodes[0] = Node(label = n1.label+n2.label, left_neigh = n1, right_neigh = n2)
			occurs[nodes[0].label] = occurs[n1.label] + occurs[n2.label]
			i = 0
			while i < len(nodes) - 1 and occurs[nodes[i].label] >= occurs[nodes[i+1].label]:
				nodes[i], nodes[i+1] = nodes[i+1], nodes[i]
				i += 1
		return BinaryTree(nodes[0], chars)
Esempio n. 23
0
 def insert(self, key, value):
     """Permette di inserire un valore all'interno del dizionario
     nella maniera corretta"""
     pair = [key, value]
     newt = BinaryTree(BinaryNode(pair))
     
     if self.tree.root == None:
         self.tree.root = newt.root
     else:
         curr = self.tree.root #nodo corrente
         pred = None             #nodo precedente che abbiamo analizzato
         while curr != None:
             pred = curr
             if key <= self.key(curr): #chiave che sto inserendo e' piu piccola di quella corrente
                 curr = curr.leftSon
             else:
                 curr = curr.rightSon
         
         if key <= self.key(pred):
             self.tree.insertAsLeftSubTree(pred, newt)
         else:
             self.tree.insertAsRightSubTree(pred, newt)
Esempio n. 24
0
def build_parse_tree(fpexp):
    stack = Stack()
    node = BinaryTree(None)
    stack.push(node)
    current = node
    for s in fpexp.split(' '):
        if s == '(':
            current.insert_left(None)
            stack.push(current)
            current = current.get_left_child()
        elif s == ')':
            current = stack.pop()
        elif s in '+-*/':
            current.set_root_value(s)
            current.insert_right(None)
            stack.push(current)
            current = current.get_right_child()
        else:
            current.set_root_value(int(s))
            current = stack.pop()

    return node
def buildParseTree(fpexp):
    #creates an empty list and then iterates through the expression
    #appending items into fpList
    #checks to see if the item in the expression is a number and if the index
    #before is a number to group them together and append together in list
    fpList = [""]
    for i in fpexp.replace(" ", ""):
        if i.isdigit() and fpList[-1].isdigit():
            fpList[-1] = fpList[-1] + i
        else:
            fpList.append(i)
    fpList.pop(0)

    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree

    for i in fpList:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in ['+', '-', '*', '/', ')']:
            currentTree.setRootVal(int(i))
            parent = pStack.pop()
            currentTree = parent
        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError

    return eTree
Esempio n. 26
0
def testFind():
    print(divider + "Executing testFind()...")
    tree = BinaryTree()
    lowerBound = 0
    upperBound = 100

    # Insert values
    for i in range(lowerBound, upperBound):
        tree.insert(Node(i))

    # Ensure all inserted values are found
    for i in range(lowerBound, upperBound):
        assert (tree.find(i, tree.root))

    # Ensure values outside of range are not found
    for i in range(-10000, lowerBound):
        assert (not tree.find(i, tree.root))

    for i in range(upperBound, 10000):
        assert (not tree.find(i, tree.root))

    print("Passed " + divider)
    def insert(self, key, value):
        newt = BinaryTree(BinaryNode([
            key, value, 0
        ]))  #Primo cambiamento e' tripletta al posto della coppia key value

        if self.tree.root == None:
            self.tree.root = newt.root
        else:
            curr = self.tree.root
            pred = None
            while curr != None:
                pred = curr
                if key <= self.key(curr):
                    curr = curr.leftSon
                else:
                    curr = curr.rightSon

            if key <= self.key(pred):
                self.tree.insertAsLeftSubTree(pred, newt)
            else:
                self.tree.insertAsRightSubTree(pred, newt)
            self.balInsert(
                newt.root
            )  #secondo cambiamento e' la chiamata del metodo per bilanciare l'albero
Esempio n. 28
0
        inorder(tree.right)
    return l


def Symmetry():
    equal = True
    sym = inorder(tree)
    length = len(sym)
    print sym, length

    while length > 1 and equal:
        first = sym.pop()
        last = sym.pop(0)
        length -= 2
        if first == last:
            equal = True
            continue
        else:
            equal = False
    print equal


tree = BinaryTree(3)
tree.insert_left(9)
tree.insert_right(20)
tree.get_left_child().insert_left(4)
tree.get_left_child().insert_right(5)
tree.get_right_child().insert_left(15)
tree.get_right_child().insert_right(7)

Symmetry()
Esempio n. 29
0
from binaryTree import BinaryTree

tree = BinaryTree(5)
tree.insert_left(4)
tree.insert_right(8)
tree.get_left_child().insert_left(11)
# tree.get_left_child().insert_right(2)
tree.get_right_child().insert_left(13)
tree.get_right_child().insert_right(4)
tree.get_left_child().get_left_child().insert_left(7)
tree.left.left.insert_right(2)
tree.right.right.insert_right(1)
tree.right.right.insert_left(5)

# def path(tree):
# 	paths = []
# 	if not (tree.left or tree.right):
# 		return [[tree.key]]    # this will return all the leaf nodes
# 	if tree.left:
# 		paths.extend([[tree.key] + child for child in path(tree.left)])
# 	if tree.right:
# 		paths.extend([[tree.key] + child for child in path(tree.right)])
# 	return paths

# k=22
# p=[]
# p=path(tree)
# print p
# for i in p:
# 	if sum(i)==k:
# 		print 1
Esempio n. 30
0
from binaryTree import BinaryTree

tree=BinaryTree(1)
tree.insert_left(2)
tree.insert_right(3)

l=[]
def inorder(tree):
	global l
	if tree==None:
		return
	else:
		inorder(tree.left)
		l.append(tree.key)
		inorder(tree.right)
	return l

def recover(root):
	y=[]
	if root==None:
		return
	p=inorder(root)
	for i in range(len(p)-1):
		if p[i]>p[i+1]:
			y.extend([p[i],p[i+1]])

	return [min(y),max(y)]

print recover(tree)
Esempio n. 31
0
		ans=[]
		line=0
		while queue:
			level=[]
			size=len(queue)
			for i in range(size):
				node=queue.pop(0)
				if node:
					if line%2==0:
						level.append(node.key)
					else:
						level.insert(0,node.key)
				
				if node.left:
					queue.append(node.left)
				if node.right:
					queue.append(node.right)

			ans.append(level)
			line+=1
		return ans

tree = BinaryTree(3)
tree.insert_left(9)
tree.insert_right(20)
tree.get_left_child().insert_left(4)
tree.get_left_child().insert_right(5)
tree.get_right_child().insert_left(15)
tree.get_right_child().insert_right(7)

print zigzag(tree)
from binaryTree import BinaryTree

tree = BinaryTree(20)
tree.insert_left(8)
tree.insert_right(22)
tree.get_left_child().insert_left(4)
tree.get_left_child().insert_right(12)
tree.get_left_child().get_right_child().insert_left(10)
tree.get_left_child().get_right_child().insert_right(14)


def lca_without_parent(root, value1, value2):
    while root != None:
        if root.key > value1 and root.key > value2:
            root = root.left
        elif root.key < value1 and root.key < value2:
            root = root.right
        else:
            return root.key


print lca_without_parent(tree, 4, 14)
Esempio n. 33
0
from binaryTree import BinaryTree

tree=BinaryTree(1)
tree.insert_left(1)
tree.insert_right('A')
tree.left.insert_left('B')
tree.left.insert_right('C')

def leaf(node):
	if not (node.right or node.left):
		return True

def huffman(root,code):
	temp=root
	if temp==None:
		return
	for i in code:
		if i=='1':
			if temp.right:
				temp=temp.right
				if leaf(temp):
					print temp.key
					temp=root
				else:
					continue

		elif i=='0':
			if temp.left:
				temp=temp.left
				if leaf(temp):
					print temp.key
Esempio n. 34
0
    print("delete nodes with one child")
    bst.delete(16)
    bst.delete(12)
    bst.preorderTraversal()

    print("delete nodes with two children")
    bst.delete(14)
    bst.preorderTraversal()

    print("delete root")
    bst.delete(20)
    bst.preorderTraversal()

    print("Validate bst", bst.validateBST())
    from binaryTree import BinaryTree
    r = BinaryTree(20)
    r.insertLeft(10)
    r.insertRight(30)
    r.leftChild.insertLeft(12)
    r.leftChild.insertRight(8)
    BinaryTree.validateBST = BinarySearchTree.validateBST
    print("Validate r", r.validateBST())
"""
Tree --->
                                        20
                              10                30
                        8         14        25      32
                               12    16
                                13     18
"""
Esempio n. 35
0
from binaryTree import BinaryTree

tree = BinaryTree(26)
tree.insert_left(10)
tree.insert_right(3)
tree.get_left_child().insert_left(6)
tree.get_left_child().insert_right(4)
tree.get_right_child().insert_right(3)

def sum_nodes(root):
	if root==None:
		return 0
	return sum_nodes(root.left) + root.key + sum_nodes(root.right)

def sumtree(root):
	if root==None or (root.left==None and root.right==None):
		return 1
	ls = sum_nodes(root.left)
	rs = sum_nodes(root.right)

	if (root.key == ls+rs) and (sumtree(root.left)) and (sumtree(root.right)):
		return 1
	return 0


print sumtree(tree)
Esempio n. 36
0
from binaryTree import BinaryTree

tree = BinaryTree(5)
tree.insert_left(4)
tree.insert_right(5)
# tree.get_left_child().insert_left(3)
# tree.get_right_child().insert_right(7)


l=[]
def check(tree):
	if tree!=None:
		if tree.left:
			if tree.left.key<tree.key:
				l.append("bST")
				check(tree.left)
			else:
				l.append("not BST")

		if tree.right:
			if tree.right.key>tree.key:
				l.append("BSt")
				check(tree.right)
			else:
				l.append("Not BSt")

	return l

print check(tree)

# def check(tree):
Esempio n. 37
0
from binaryTree import BinaryTree

tree = BinaryTree(3)
tree.insert_left(5)
tree.insert_right(1)
tree.get_left_child().insert_left(6)
tree.get_left_child().insert_right(2)
tree.get_right_child().insert_left(0)
tree.get_right_child().insert_right(8)
#tree.get_left_child().get_left_child().insert_left(8)
tree.get_left_child().get_right_child().insert_left(7)
tree.get_left_child().get_right_child().insert_right(4)
# tree.get_right_child().get_left_child().insert_left(16)
# tree.get_right_child().get_right_child().insert_right(27)

l=[]
def inorder(tree):
	global l
	if tree==None:
		return
	else:
		inorder(tree.left)
		l.append(tree.key)
		inorder(tree.right)
	return l

def depth(root,node):
	count=0
	if root==None:
		return 0
	q=[root]