Ejemplo n.º 1
0
def create_tree_from_nested_list(nested_list):
    if nested_list == None:
        return None
    head = BinaryTree(nested_list[0])
    head.set_left(create_tree_from_nested_list(nested_list[1]))
    head.set_right(create_tree_from_nested_list(nested_list[2]))
    return head
Ejemplo n.º 2
0
	def __init__(self,filename):
		self.file = open(filename,'w+')
		self.blocksBySize = BinaryTree()
		self.blocksByPosition = BinaryTree()
		self.blocksByIndex = dict()
		self.loadDeletedBlocks()
		self.maxIndex = -1
Ejemplo n.º 3
0
def really_create_tree_from_flat_list(flat_list, pos):
    if pos >= len(flat_list):
        return None
    if flat_list[pos] == None:
        return None
    head = BinaryTree(flat_list[pos])
    head.set_left(really_create_tree_from_flat_list(flat_list, pos * 2))
    head.set_right(really_create_tree_from_flat_list(flat_list, pos * 2 + 1))
    return head
Ejemplo n.º 4
0
def make_bst(lst, start, end):
    if end - start < 0:
        return None
    # Base case: one element
    if end - start == 0:
        return BinaryTree(lst[start])
    mid = start + end // 2      # Center, leaning left
    temp = BinaryTree(lst[mid])
    temp.left = make_bst(lst, start, mid-1)
    temp.right = make_bst(lst, mid+1, end)
    return temp
Ejemplo n.º 5
0
def test_question_five():
    print('\n====================\n Testing Question 5\n====================')

    flat_list = [None, 10, 5, 15, None, None, 11, 22] 
    #my_tree = create_tree_from_flat_list(flat_list) 
    my_tree = [None, 10, 5, 15, None, None, 11, 22]
    a = BinaryTree(10)
    a.set_left(BinaryTree(5))
    a.set_right(BinaryTree(6))

    print(Asst2.sum_tree(a))
Ejemplo n.º 6
0
    def insert(self, o):
        successful = BinaryTree.insert(self, o)
        if not successful:
            return False # o is already in the tree
        else:
            self.balancePath(o) # Balance from o to the root if necessary

        return True # o is inserted
class InvertedFile:
    """A indexing file that stores all the words from a file as well as the indices of all the places in the file that
    each word appears.
    """
    def __init__(self):
        self.data = dict()                      # dict contains: { word: [indices in doc where word is found]}
        self.order = BinaryTree()               # sorted binary tree maintains the order of items

    def __contains__(self, item):
        return item in self.data

    def next(self):
        for item in self.order.in_order():
            yield item, self.data[item]

    def __getitem__(self, key):
        if isinstance(key, str):                # if indexing by string: talk to dict
            return self.data[key]
        else:
            return self.order[key]              # if indexing numerically: talk to tree

    def fetch(self, path):
        """Add all words in the given file to this inverted file. Case is ignored when adding words
        :param path: The path to the file from which to retrieve words
        """
        with open(path, 'r') as document:
            length = 0                                               # total of all line lengths
            for line in document:
                for match in re.finditer('[\w-]+', line):            # find all words in line
                    word = match.group().lower()
                    index = length + match.start()
                    if word in self.data:                            # add word to dict
                        self.data[word].append(index)
                    else:
                        self.data.update({word: [index]})
                    self.order.add(word)                             # AND add to ordered binary tree
                length += len(line)
Ejemplo n.º 8
0
def main():
    """pass"""
    b = BinaryTree()
    print(CYN)
    print("size:", b.getSize())
    print("root:", b.getRoot())
    print(NC)
    print("{}Creating 10 elements... [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] {}".format(BLU, NC))

    [b.insert(thing) for thing in [0,1,2,3,4,5,6,7,8,9] ]

    print(CYN)
    print("size:", b.getSize())
    print("root:", b.getRoot().element)
    print(NC)

    b.breadth()
Ejemplo n.º 9
0
    def balancePath(self, o):
        path = BinaryTree.path(self, o);
        for i in range(len(path) - 1, -1, -1): 
            A = path[i]
            self.updateHeight(A)
            parentOfA = None if (A == self.root) else path[i - 1]

            if self.balanceFactor(A) == -2:
                if self.balanceFactor(A.left) <= 0:
                    self.balanceLL(A, parentOfA) # Perform LL rotation
                else:
                    self.balanceLR(A, parentOfA) # Perform LR rotation
            elif self.balanceFactor(A) == +2:
                if self.balanceFactor(A.right) >= 0:
                    self.balanceRR(A, parentOfA) # Perform RR rotation
                else:
                    self.balanceRL(A, parentOfA) # Perform RL rotation
Ejemplo n.º 10
0
def main():
	bookTree = BinaryTree("Book")
	bookTree.insertLeft("Chapter1")
	bookTree.insertRight("Chapter2")

	chap1 = bookTree.getLeftChild()
	chap2 = bookTree.getRightChild()

	chap1.insertLeft("Sec 1.1")
	chap1.insertRight("Sec 1.2")

	chap2.insertLeft("Sec 2.1")
	chap2.insertRight("Sec 2.2")

	pre = preorder(bookTree)
	post = postorder(bookTree)
	inO = inorder(bookTree)
	print("In pre order: ", pre)
	print("In post order: ", post)
	print("In order: ", inO )
"""
Validate BST: Implement a function to check if a binary tree is a binary search tree.
"""
import pytest

from BinaryTree import BinaryTree


def validate_bst_node(node, left_bound, right_bound):
    if node is None:
        return True
    
    return left_bound <= node.value < right_bound and validate_bst_node(node.left,
                                                                        left_bound,
                                                                        node.value) and validate_bst_node(node.right,
                                                                                                          node.value,
                                                                                                          right_bound)


def validate_bst(root):
    return validate_bst_node(root, -float('inf'), float('inf'))


@pytest.mark.parametrize('binary_tree, expected', [
    (BinaryTree(10, BinaryTree(5, BinaryTree(2), BinaryTree(7)), BinaryTree(15, BinaryTree(12), BinaryTree(17))), True),
    (BinaryTree(1, BinaryTree(0, BinaryTree(-1, BinaryTree(-2)))), True),
    (BinaryTree(5, BinaryTree(3, BinaryTree(2), BinaryTree(6)), BinaryTree(10)), False)
])
def test_validate_bst(binary_tree, expected):
    assert validate_bst(binary_tree) == expected
class Test(unittest.TestCase):
    def setUp(self):
        self.bst = BinaryTree()
        self.bst.insert(5)
        self.bst.insert(3)
        self.bst.insert(4)
        self.bst.insert(2)
        self.bst.insert(1)
        self.bst.insert(6)
        self.bst.insert(9)

    def test_balanced_bst(self):
        self.assertTrue(is_balanced(self.bst))
        self.bst.insert(7)
        self.bst.insert(8)
        self.assertFalse(is_balanced(self.bst))

    def test_balanced_bst_optimization(self):
        self.assertTrue(is_balanced_with_optimization(self.bst))
        self.bst.insert(7)
        self.bst.insert(8)
        self.assertFalse(is_balanced_with_optimization(self.bst))
Ejemplo n.º 13
0
 def add(self, key: object, value: object) -> bool:
     p = self.find_last(key)
     return self.add_child(p, BinaryTree.Node(key, value))
        curr_node = stack.pop()
        if curr_node.right:
            stack.append(curr_node.right)
        if curr_node.left:
            stack.append(curr_node.left)
        if prev_node:
            prev_node.left = None
            prev_node.right = curr_node
        prev_node = curr_node
        
if __name__=='__main__':
    ''' The tree is:
                     1
                   /   \ 
                 2      3
                / \    / \
               4   5  8   9
                  / \    / \
                 6   7  10  11
                /
               12
    '''
    t=BinaryTree()
    pre_order=[1,2,4,5,6,12,7,3,8,9,10,11]
    in_order=[4,2,12,6,5,7,1,8,3,10,9,11]
    t.create_tree(pre_order, in_order)
    flattern_bt2list(t.root)

    t.pre_order_print(t.root)
    print 
    t.in_order_print(t.root)
Ejemplo n.º 15
0
            4164(3197+317+328+322)
       
'''

from BinaryTree import BinaryTree
def sum_root_to_leaf(r):
    if not r:
        return 0
    return sum_root_to_leaf_helper(r, 0, [0])

def sum_root_to_leaf_helper(r, curr_num, sum):
    if not r:
        return 
    if not r.left and not r.right:
        sum[0]+=curr_num*10+r.data
        return sum[0]
    curr_num = curr_num *10 + r.data
    sum_root_to_leaf_helper(r.left, curr_num, sum)
    sum_root_to_leaf_helper(r.right, curr_num, sum)
    return sum[0]

if __name__=='__main__':
    t=BinaryTree()
    pre_order=[3,1,9,7,7,2,8,2]
    in_order=[7,9,1,7,3,8,2,2]
    t.create_tree(pre_order, in_order)
    
    
    print sum_root_to_leaf(t.root)
    
    
Ejemplo n.º 16
0
trrce(q)
q.remove()
trrce(q)
print("isEmpty? ",s.isEmpty())

print("--------------BinaryTree----------------")

tree = '''

			1
		2		3	
	4				5	

'''
print(tree)
r = BinaryTree() #root
rll = BinaryTree() 
rll.makeTree(4,None,None)
rr = BinaryTree()
rr.makeTree(2,rll,None)
rrr = BinaryTree()
rrr.makeTree(5,None,None) 
rl = BinaryTree()
rl.makeTree(3,None,rrr) 
r.makeTree(1,rr,rl)

print("preOrder")
r.preOrder(r)  
print("inOrder")
r.inOrder(r)  
print("postOrder")
Ejemplo n.º 17
0
    else:
        return None


# O(n)
def isChildNode(node, n1):
    if node == None:
        return False

    if node.obj is n1.obj:
        return True
    return isChildNode(node.left, n1) or isChildNode(node.right, n1)


tree = Node("0")
tree.left = Node("1")
tree.right = Node("2")
tree.left.left = Node("3")
tree.left.right = Node("4")
tree.right.left = Node("5")
tree.right.right = Node("6")
tree.right.right.left = Node("10")
tree.right.right.right = Node("7")
tree.right.right.right.right = Node("8")
BinaryTree.print(tree)

node = get_Smallest_Common_Ancestor(tree, tree.right,
                                    tree.right.right.right.right)
print("Smalest common ancestor: {}".format(node.obj))
Ejemplo n.º 18
0
class TreeTest(unittest.TestCase):

    #===============Initial==========================
    def setUp(self):
        self.b = BinaryTree(Node(12))
        self.b.add(15)
        self.b.add(18)
        self.b.add(4)
        self.b.add(9)

    def tearDown(self):
        del self.b

#==============Testing===================

    """
    BinaryTree
        -add(value):
        -del_node(value):
        -find(value, from_node=None)
        -min_max()
        -get_node_list()
    """
    def test_add(self):
        val = 8
        parent = self.b.root.left_child.right_child
        self.b.add(val)
        self.assertEqual(parent.left_child.value, val)
        print(self.b.display())

    def test_del(self):
        x = self.b.root.right_child.right_child
        self.assertNotEqual(x, None)
        self.b.del_node(x.value)
        self.assertTrue(self.b.root.right_child.right_child == None)

    def test_find(self):
        res = self.b.find(15)
        parent = self.b.root
        role = "right"
        self.assertNotEqual(res["node"], None)
        self.assertEqual(parent, res["parent"])
        self.assertEqual(role, res["role"])

    def test_min_max(self):
        self.b.add(1)
        self.b.add(17)
        self.b.add(88)
        self.assertTrue(self.b.min_max2() == [1, 88])
Ejemplo n.º 19
0
 def setUp(self):
     self.b = BinaryTree(Node(12))
     self.b.add(15)
     self.b.add(18)
     self.b.add(4)
     self.b.add(9)
	def setUp(self):
		print "=========== Running BinaryTree Test ==========="
		self.b = BinaryTree()
Ejemplo n.º 21
0
Chapter 4 Question 4

Given a binary tree, convert it to a set of linked lists, each list representing
a layer of the tree.

(I'm kind of cheating: instead of a stict linked list, I'm using regular
lists. Same principle, though.)
"""

from BinaryTree import BinaryTree

def layerize(root, current_layer=0, lst=None):
    if not lst:
        lst = list()
    if len(lst) < current_layer+1:
        lst.append(list())
    lst[current_layer].append(root.data)
    if root.left:
        lst = layerize(root.left, current_layer+1, lst)
    if root.right:
        lst = layerize(root.right, current_layer+1, lst)

    return lst

if __name__ == '__main__':
    root = BinaryTree(1)
    root.left = BinaryTree(2)
    root.right = BinaryTree(3)
    root.right.right = BinaryTree(4)
    print(layerize(root))
Ejemplo n.º 22
0
#!/usr/bin/python

from BinaryTree import BinaryTree


r = BinaryTree(10)
r.insertLeft(5)
r.getLeftChild().insertRight(6)
r.insertRight(15)
r.getRightChild().insertLeft(11)
r.getRightChild().insertRight(100)

print r.getRootVal()
print r.getLeftChild().getRootVal()
print r.getLeftChild().getRightChild().getRootVal()
print r.getRightChild().getRootVal()
print r.getRightChild().getLeftChild().getRootVal()
print r.getRightChild().getRightChild().getRootVal()

print

def preorder(tree):
    if tree:
        print(tree.getRootVal())
        preorder(tree.getLeftChild())
        preorder(tree.getRightChild())

preorder(r)
print
r.preorder()
print
    # if r is leaf or r has no left child or r has no right child, the min depth is current depth
    if not r:
        return depth-1
    
    left_min_depth = get_min_depth(r.left, depth+1)
    right_min_depth = get_min_depth(r.right, depth+1)
    
    if r.left and not r.right:
        return left_min_depth
    if not r.left and r.right:
        return right_min_depth
    return min(left_min_depth, right_min_depth)


if __name__=='__main__':
    ''' The tree is:
                     1
                   /   \ 
                 2      3
                / \    / \
               4   5  8   9
                  / \    / \
                 6   7  10  11
                /
               12
    '''
    t=BinaryTree()
    pre_order=[1,2,4,5,6,12,7,3,8,9,10,11]
    in_order=[4,2,12,6,5,7,1,8,3,10,9,11]
    t.create_tree(pre_order, in_order)
    print get_min_depth(t.root,1)
Ejemplo n.º 24
0
if __name__=='__main__':
    ''' T1 is:
                     1
                   /   \ 
                 2      3
                / \    / \
               4   5  8   9
                  / \    / \
                 6   7  10  11
                /
               12
               
               
        T2 is :
                     3
                    /  \
                   8    9
                       / \
                     10  11
    '''
    t1=BinaryTree()
    pre_order=[1,2,4,5,6,12,7,3,8,9,10,11]
    in_order=[4,2,12,6,5,7,1,8,3,10,9,11]
    r1=t1.create_tree(pre_order, in_order)
    
    t2=BinaryTree()
    pre_order=[3,8,9,10,11]
    in_order=[8,3,10,9,11]
    r2=t2.create_tree(pre_order, in_order)
    print is_subtree(r1,r2)
Ejemplo n.º 25
0
def Decode_by_Tree(T, codeString):
    space = ' '
    temp = BinaryTree(space)
    temp = T
    print(codeString)
    phraseString = ""
    check = True
    Decode_phrase_list = []
    Decode_phrase_list.append(phraseString)
    Decode_phrase_list.append(check)
    codeStringlist = []
    for n in codeString:
        codeStringlist.append(n)
    foundchar = False
    while (check and (len(codeStringlist) > 0)):
        digit = codeStringlist.pop(0)
        if (digit == '0'):
            print("Go Left")
            if (temp.getLeftChild() != None):
                if (temp.getLeftChild().getRootVal() == space):
                    temp = temp.getLeftChild()
                    if ((len(codeStringlist) == 0)):
                        check = False
                        print(
                            " Erorr _________________Left_______(len (codeStringlist) == 0)________________",
                            temp.getRootVal())

                else:
                    print(temp.getLeftChild().getRootVal())
                    phraseString = phraseString + temp.getLeftChild(
                    ).getRootVal()
                    print(phraseString)
                    temp = T
            else:
                check = False
                print(" Erorr _________________Left_______________________",
                      temp.getRootVal())
        else:
            if (digit == '1'):
                print("Go Right")
                if (temp.getRightChild() != None):
                    if (temp.getRightChild().getRootVal() == space):
                        temp = temp.getRightChild()
                        if ((len(codeStringlist) == 0)):
                            check = False
                            print(
                                " Erorr _________________Right_______(len (codeStringlist) == 0)________________",
                                temp.getRootVal())
                    else:
                        print(temp.getRightChild().getRootVal())
                        phraseString = phraseString + temp.getRightChild(
                        ).getRootVal()
                        print(phraseString)
                        temp = T
                else:
                    check = False
                    print(
                        " Erorr ___________________Right_____________________",
                        temp.getRootVal())

    Decode_phrase_list[0] = phraseString
    Decode_phrase_list[1] = check
    return Decode_phrase_list
Ejemplo n.º 26
0
def main():
    bt = BinaryTree()
    dataSet = set([])
    # values = ['F', 'B', 'A', 'D', 'C', 'E', 'G', 'I', 'H']
    values = [25, 15, 40, 10, 20, 30, 50, 18, 22, 27, 45, 60, 42, 47, 49]
    for r in range(random.randint(7, 12)):
        n = random.randint(1, 100)
        dataSet.add(n)

    print ("Inserting into Binary Tree: ")
    # for data in dataSet:
    for data in values:
        bt.insert(data)
        print (data, sep=" ", end=" ")
    print ()

    print ("Inorder: ")
    bt.inorder()
    print ("Preorder: ")
    bt.preorder()
    print ("postorder: ")
    bt.postorder()
    print ("Binary Tree Size: ", bt.size())
    print ("Max Depth: ", bt.maxdepth())
    print ("Min value in BST: ", bt.minvalue())
    print ("Max value in BST: ", bt.maxvalue())

    targetsums = [50, 78, 82, 97, 150]
    for target in targetsums:
        ans = bt.haspathsum(target)
        print ("Sum: %d in binary tree: %s" % (target, ans))

    print ("print all the root to leaf paths in binary tree")
    bt.printpaths()
    print ("Mirroring the binary tree: ")
    bt.mirror()
    bt.inorder()

    bt = BinaryTree()
    values = [2, 3, 1]
    print ("Inserting into Binary Tree: ")
    # for data in dataSet:
    for data in values:
        bt.insert(data)
        print (data, sep=" ", end=" ")
    print ()
    bt.inorder()
    print ("After doing double tree: ")
    bt.doubletree()
    bt.inorder()

    bt1 = BinaryTree()
    bt2 = BinaryTree()
    # values = ['F', 'B', 'A', 'D', 'C', 'E', 'G', 'I', 'H']
    values = [25, 15, 40, 10, 20, 30, 50, 18, 22, 27, 45, 60, 42, 47, 49]
    print ("Inserting into Binary Tree: ")
    # for data in dataSet:
    for data in values:
        bt1.insert(data)
        bt2.insert(data)
        print (data, sep=" ", end=" ")
    print ()
    bt1.inorder()
    bt2.inorder()
    comp = bt1.sametree(bt2)
    print ("Are the trees same: ", comp)
    print ("is bt1 BST: ", bt1.isbst1())
    print ("is bt2 BST: ", bt2.isbst1())
    bt2.mirror()
    print ("is bt2 BST after mirroring: ", bt2.isbst1())

    bt1 = BinaryTree()
    bt2 = BinaryTree()
    for data in values:
        bt1.insert(data)
        bt2.insert(data)
        print (data, sep=" ", end=" ")
    print ()
    print ("is bt1 BST (efficient version): ", bt1.isbst2())
    print ("is bt2 BST (efficient version): ", bt2.isbst2())
    bt2.mirror()
    print ("is bt2 BST after mirroring(efficient version): ", bt2.isbst2())

    for i in range(1,13):
        tot = bt.counttrees(i)
        print ("%d nodes: %d unique BSTs" % (i, tot))
def main():
    tree = BinaryTree()
    tree.insert("George")
    tree.insert("Michael")
    tree.insert("Tom")
    tree.insert("Adam")
    tree.insert("Jones")
    tree.insert("Peter")
    tree.insert("Daniel")
    printTree(tree)

    print("\nAfter delete George:")
    tree.delete("George")
    printTree(tree)

    print("\nAfter delete Adam:")
    tree.delete("Adam")
    printTree(tree)

    print("\nAfter delete Michael:")
    tree.delete("Michael")
    printTree(tree)
Ejemplo n.º 28
0
    if not r.parent:
        return None
    else:
        return r.parent
def get_next(r):
    if r.right:
        return get_leftmost_child(r.right)
    else:
        return get_first_right_parent(r)
    
    
if __name__=='__main__':
    ''' The tree is:
                     20
                   /   \ 
                 10     30
                / \    
               5   15  
              / \   \
             3   7   17  
                
               
    '''
    t=BinaryTree();
    pre_order=[20,10,5,3,7,15,17,30]
    in_order=[3,5,7,10,15,17,20,30]
    root=t.create_tree(pre_order, in_order)
    for node in in_order:
        r=t.get_TreeNode_NR(root,node)
        print "r is ", r
        print "r's next is", get_next(r)
Ejemplo n.º 29
0
 def setData(self, data):
     BinaryTree.setData(self, data)
     if (self.getHeight() < 0):
         self.setHeight(0)
 def __init__(self):
     self.data = dict()                      # dict contains: { word: [indices in doc where word is found]}
     self.order = BinaryTree()               # sorted binary tree maintains the order of items
	graph.addEdge(2,9)
	graph.addEdge(3,4)
	graph.addEdge(4,6)
	graph.addEdge(4,2)
	graph.addEdge(4,9)
	graph.addEdge(5,10)
	graph.addEdge(5,3)
	graph.addEdge(6,3)
	graph.addEdge(7,8)
	graph.addEdge(8,3)
	graph.addEdge(9,10)
	graph.addEdge(10,4)
	graph.findVertex(2)
	graph.findVertex(3)
	graph.findVertex(4)
	graph.findVertex(5)
	graph.findVertex(6)
	print("Graph Test Completed.")
	print("-------------------------------------------------------")
	print("This is the tree test. It does not work all the way.")
	tree = BinaryTree(1)
	tree.add(2,1)
	tree.add(3,1)
	tree.add(10,1)
	tree.add(4,2)
	tree.add(5,2)
	tree.remove(2)
	tree.remove(1)
	print("Tree Test Completed.")

class TestBinaryTree(unittest.TestCase):

	def setUp(self):
		print "=========== Running BinaryTree Test ==========="
		self.b = BinaryTree()
	
	def tearDown(self):
		print "================================================"

	def test_add_integers_and_print(self):
		# Run by unittest - adds 10 nodes in tree, then prints to display they were added correctly
		# State before: Empty tree
		# State after: Tree with 10 nodes
		self.b.add(1, None)
		self.b.add(2, 1)
		self.b.add(3, 1)
		self.b.add(4, 2)
		self.b.add(5, 2)
		self.b.add(6, 3)
		self.b.add(7, 3)
		self.b.add(8, 4)
		self.b.add(9, 4)
		self.b.add(10, 5)

		self.b.print_tree()
		
	def test_delete_and_print(self):
		# Run by unittest - adds 10 nodes in tree, deletes 2, then prints to ensure they are correctly deleted
		# State before: Empty tree
		# State after: Tree with 8 nodes
		self.b.add(1, None)
		self.b.add(2, 1)
		self.b.add(3, 1)
		self.b.add(4, 2)
		self.b.add(5, 2)
		self.b.add(6, 3)
		self.b.add(7, 3)
		self.b.add(8, 4)
		self.b.add(9, 4)
		self.b.add(10, 5)
		self.b.delete(10)
		self.b.delete(8)

		self.b.print_tree()
Ejemplo n.º 33
0
def makeparsetree(expression):
    now = BinaryTree(None)
    parent = Stack()
    for item in expression:
        if item in openbraket:
            now.addleft(None)
            parent.push(now)
            now = now.getleft()

        elif item in endbraket:
            if not parent.isEmpty():
                now = parent.pop()

        elif item in operators:
            now.setdata(item)
            parent.push(now)
            now.addright(None)
            now = now.getright()

        else :
            now.setdata(int(item))
            now = parent.pop()

        """else:
            return "Invalid expression"""

        # print "Read ", item                             #debug line

    return now
Ejemplo n.º 34
0
            recursive(current_root, preorder_right, inorder_right, 'right')

    recursive(btree.root, preorder, inorder, 'None')

    return btree


'''
Still recursive solution
'''


def solution2(preorder, inorder):
    pass


if __name__ == '__main__':
    element_list = list(np.random.choice(100, size=20, replace=False))
    btree = BinaryTree(element_list)
    preorder = btree.preorder_iterative(btree.root)
    inorder = btree.inorder_iterative(btree.root)
    print(preorder, inorder)
    reconstructed_btree = solution1(preorder, inorder)
    reorder = reconstructed_btree.preorder_iterative(reconstructed_btree.root)
    inorder = reconstructed_btree.inorder_iterative(reconstructed_btree.root)
    print(preorder, inorder)
    reconstructed_btree = solution2(preorder, inorder)
    preorder = reconstructed_btree.preorder_iterative(reconstructed_btree.root)
    inorder = reconstructed_btree.inorder_iterative(reconstructed_btree.root)
    print(preorder, inorder)
Ejemplo n.º 35
0
 def __init__(self):
     BinaryTree.__init__(self)
     self.height = 1
#!/usr/bin/env python3

#Authors: M269 Module Team
#Date: 19/1/13

from BinaryTree import BinaryTree

#Create a node and reference representation of the
#tree shown in Figure 6.6(a) on p. 238 of Ranum and Miller.
#The nodes are added level by level working downwards.
print('Creating tree')
#Level 0
t = BinaryTree('a')

#Level 1
t.insertLeft('b')
t.insertRight('c')

#Level 2
t.getLeftChild().insertLeft('d')
t.getLeftChild().insertRight('e')
t.getRightChild().insertLeft('f')


#Function to convert from node and reference
#to list of lists representation.
def makeLists(tr):
    #If tree is empty the list is empty
    if tr == None:
        return []
    #Otherwise call the function recursively
Ejemplo n.º 37
0
 def __init__(self, nil=None):
     BinaryTree.__init__(self)
     self.n = 0
     self.nil = nil
Ejemplo n.º 38
0
from BinaryTree import BinaryTree
import sys


def max_path_sum(r):
    max_sum = [-sys.maxint]
    # pass in max_sum as a list to modify it's value in recursion
    max_path_sum_helper(r, max_sum)
    return max_sum[0]


def max_path_sum_helper(r, max_sum):
    if not r:
        return 0
    # get left and right subtrees' max sum path
    left_max = max(0, max_path_sum_helper(r.left, max_sum))
    right_max = max(0, max_path_sum_helper(r.right, max_sum))
    # update max_sum
    max_sum[0] = max(max_sum[0], r.data + left_max + right_max)
    # can only return one subtree path, return the larger one
    return max(r.data + left_max, r.data + right_max)


if __name__ == '__main__':
    t = BinaryTree()
    pre_order = [-1, 1, 23, 2, 24, 9, 7, 6]
    in_order = [23, 1, 24, 2, -1, 7, 9, 6]
    t.create_tree(pre_order, in_order)
    t.in_order_print(t.root)
    print
    print max_path_sum(t.root)
Ejemplo n.º 39
0
def generate_bt(points_to_insert):
    binary_tree = BinaryTree()
    for p in points_to_insert:
        binary_tree.add(p)
    return binary_tree
Ejemplo n.º 40
0
    else:
        return r.parent


def get_next(r):
    if r.right:
        return get_leftmost_child(r.right)
    else:
        return get_first_right_parent(r)


if __name__ == '__main__':
    ''' The tree is:
                     20
                   /   \ 
                 10     30
                / \    
               5   15  
              / \   \
             3   7   17  
                
               
    '''
    t = BinaryTree()
    pre_order = [20, 10, 5, 3, 7, 15, 17, 30]
    in_order = [3, 5, 7, 10, 15, 17, 20, 30]
    root = t.create_tree(pre_order, in_order)
    for node in in_order:
        r = t.get_TreeNode_NR(root, node)
        print "r is ", r
        print "r's next is", get_next(r)
Ejemplo n.º 41
0
def Encode_by_Tree(charcodelist):
    space = ' '
    myTree_check_list = []
    mytree = BinaryTree(space)
    check = True
    myTree_check_list.append(mytree)
    myTree_check_list.append(check)
    print(myTree_check_list)
    for i in range(0, len(charcodelist) - 1):
        print("#####################################")
        if (not check):
            break
        line = charcodelist[i]
        mychar = line[0]
        mycode = line[1]
        mycode = mycode + mychar
        temp = BinaryTree(space)
        temp = mytree
        for digit in range(0, len(mycode) - 1):
            if (digit == (len(mycode) - 2)):
                digit = digit + 1

            print("-----------------------------------")
            if (mycode[digit] == '0'):
                print("Go left")
                if (temp.getLeftChild() == None):
                    print("Add Left")
                    temp.insertLeft(space)
                    temp = temp.getLeftChild()
                else:
                    if (temp.getLeftChild().getRootVal() == space):
                        print("just go left ")
                        temp = temp.getLeftChild()
                    else:
                        check = False
                        print(
                            " Erorr ______on going left________________________________________",
                            mycode[len(mycode) - 1])
                        break

            else:
                if (mycode[digit] == '1'):
                    print("Go Right")
                    if (temp.getRightChild() == None):
                        print("Add Right")
                        temp.insertRight(space)
                        temp = temp.getRightChild()
                    else:
                        if (temp.getRightChild().getRootVal() == space):
                            print("just go Right")
                            temp = temp.getRightChild()
                        else:
                            check = False
                            print(
                                " Erorr ______on going Right________________________________________",
                                mycode[len(mycode) - 1])
                            break

                else:
                    if (mycode[len(mycode) - 2] == '0'):
                        try:
                            if (temp.getLeftChild().getRootVal() != None):
                                check = False
                                print(
                                    " Erorr ______on Adding Left ________________________________________",
                                    mycode[len(mycode) - 1])
                                break
                        except AttributeError:
                            temp.insertLeft(mycode[digit])
                            print("Adding to the left of the tree ",
                                  mycode[digit])
                    if (mycode[len(mycode) - 2] == '1'):
                        try:
                            if (temp.getRightChild().getRootVal() != None):
                                check = False
                                print(
                                    " Erorr ______on Adding Right ________________________________________",
                                    mycode[len(mycode) - 1])
                                break
                        except AttributeError:
                            temp.insertRight(mycode[digit])
                            print("Adding to the Right of the tree ",
                                  mycode[digit])

        print(charcodelist[i])
    myTree_check_list[0] = mytree
    myTree_check_list[1] = check
    return myTree_check_list
Ejemplo n.º 42
0
                        print("found bacteria {}".format(bact.name))
                        line_length = _SPACE_PER_LEVEL - len(bact.name)
                        horizontal_line = ""
                        if ht != 0:
                            #Build a line of approrpiate length for the diagram
                            for j in range(0, line_length):
                                horizontal_line += "-"
                            horizontal_line += "|"
                        line = bact.name + horizontal_line + line
                    else:
                        line = _EMPTY_LINE + line
            f.write(line)


if __name__ == '__main__':
    timothy = Bacteria(_LENGTH, _POS_X, _POS_Y, _AGE, "timothy")
    tree = BinaryTree(timothy)
    # divide(tree)
    #Run for i units of time
    for i in range(_TIME):
        children = tree.getLiveBacteria()
        for child in children:
            if shouldDivide(child.root):
                divide(child)
            if (_DEBUG):
                print(child.root.name)
                print("Age: {}".format(str(child.root.age)))
                print("Length: {}".format(str(child.root.len)))
        tree.ageTree()
        print(tree.root)
Ejemplo n.º 43
0
def convertToBinaryTree(treeRoot, nodelist):
    if not treeRoot.children:
        node = next(x for x in nodelist if x.id == treeRoot.id)
        newNode = BinaryTree("tmp",
                             BinaryTree(node.getVal()))  # poprawi typ oda
        return newNode

    if len(treeRoot.children) == 1:
        newNode = convertToBinaryTree(treeRoot.children[0], nodelist)
        if newNode.right is None:
            newNode.right = BinaryTree(treeRoot.getVal())
        else:
            parent = BinaryTree("tmpParent1", newNode,
                                BinaryTree(treeRoot.getVal()))
            return parent

    parent = None
    for child in treeRoot.children:
        newNode = convertToBinaryTree(child, nodelist)
        if parent is None:
            parent = newNode

        if parent.right is None:
            parent.right = BinaryTree(treeRoot.getVal())
        else:
            newParent = BinaryTree("tmpParent2", parent, newNode)
            parent = newParent
    return parent
Ejemplo n.º 44
0
from BinaryTree import BinaryTree
from BinaryTree import Traversal

if __name__ == '__main__':
    print("Binary TREE")

    bt = BinaryTree()
    bt.insert(3)
    bt.insert(1)
    bt.insert(2)
    bt.insert(4)
    bt.insert(5)
    bt.insert(10)
    bt.insert(7)
    bt.insert(73)
    bt.insert(23)
    bt.print()
    bt.print(traversal_type=Traversal.REVERSE)
    # bst.print(traversal_type=Traversal.PREORDER)
    # bst.print(traversal_type=Traversal.POSTORDER)
    # bst.print(traversal_type=Traversal.INORDER)

    # print('\n')
    # print('After deleting: ')
    # bst.set_root(bst.delete_node(bst.get_root(), 2))
    # bst.set_root(bst.delete_node(bst.get_root(), 73))
    # bst.set_root(bst.delete_node(bst.get_root(), 3))
    # bst.set_root(bst.delete_node(bst.get_root(), 1))
    # bst.set_root(bst.delete_node(bst.get_root(), 4))
    # bst.print()
    # bst.set_root(bst.delete_node(bst.get_root(), 7))
                que.put(node.get_right())
        return node.data


### REVISIT THIS #######


def delete_node(root):
    if root is None:
        return
    else:
        que = queue.Queue()
        que.put(root)
        if not que.empty():
            node = que.get()
            if node.get_left():
                que.put(node.get_left())
            if node.get_right():
                que.put(node.get_right())
        root.data, node.data = node.data, root.data
        del node


if __name__ == "__main__":
    tree = BinaryTree()
    for i in range(1, 10):
        tree.add_node(i)

    print(deepest_node(tree.root))
    delete_node(tree.root)
    tree.level_order()
Ejemplo n.º 46
0
from BinaryTree import BinaryTree, Node
from getHeightOfBT import getHeightOfBT
from printElementsAtAGivenLvl import printElementsAtAGivenLevel

tree = BinaryTree()
tree.createRootNode(2, None, None)
tree.root.left = Node(7, None, None)
tree.root.left.left = Node(2, None, None)
tree.root.left.right = Node(6, None, None)
tree.root.left.right.left = Node(5, None, None)
tree.root.left.right.right = Node(11, None, None)

tree.root.right = Node(5, None, None)
tree.root.right.right = Node(9, None, None)
tree.root.right.right.left = Node(4, None, None)

# levelwiseLotOfBT
# ************************************************************************************************************************


def levelwiseLotOfBT(node):
    treeHeight = getHeightOfBT(node)
    for level in range(1, treeHeight + 2):
        print("\n Level " + str(level) + ":-")
        printElementsAtAGivenLevel(node, level)


# ************************************************************************************************************************

print("Levelwise LOT of the given tree is: ")
levelwiseLotOfBT(tree.root)
Ejemplo n.º 47
0
#      4   5
#
# Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
# 如何求一颗树的深度


def depth(rt):
    if rt is None:
        return 0
    leftdepth = depth(rt.lchild)
    rightdepth = depth(rt.rchild)
    return max(leftdepth, rightdepth) + 1


def diameterOfBinaryT(rt):
    maxD = 0
    ld = depth(rt.lchild)
    lr = depth(rt.rchild)
    maxD = max(maxD, ld + lr)
    return maxD


if __name__ == "__main__":
    from BinaryTree import BinaryTree

    binary_tree = BinaryTree()
    for i in range(1, 5):
        binary_tree.insert(i)
    binary_tree.traverse()

    print(diameterOfBinaryT(binary_tree.root))
Ejemplo n.º 48
0
 def new_node(self, x):
     u = BinaryTree.Node(x)
     u.left = u.right = u.parent = self.nil
     return u
Ejemplo n.º 49
0
def test():
    tree = BinaryTree()
    tree.print()
    tree.insert(8)
    tree.insert(3)
    tree.insert(10)
    tree.insert(1)
    tree.insert(6)
    tree.insert(14)
    tree.insert(4)
    tree.insert(7)
    tree.insert(13)
    tree.print()
    try:
        tree.insert(14)  # Repetido, debe mostrar mensaje de error
    except KeyError:
        print("El nodo con llave 14 ya se encuentra en el árbol")
    try:
        tree.insert(1)  # Repetido, debe mostrar mensaje de error
    except KeyError:
        print("El nodo con llave 1 ya se encuentra en el árbol")
    print("Mínimo:", tree.minimum().key)
    print("Máximo:", tree.maximum().key)
    tree.search(4)
    tree.search(8)
    tree.search(13)
    tree.search(2)
    tree.search(15)
    tree.delete(7)  # Borrando el 7 (sin hijos)
    tree.print()
    tree.delete(10)  # Borrando el 10 (solo hijo der)
    tree.print()
    tree.delete(6)  # Borrando el 6 (solo hijo izq)
    tree.print()
    tree.delete(3)  # Borrando el 3 (ambos hijos)
    tree.print()
    try:
        tree.delete(3)  # Borrando el 3 (nodo no existe)
    except KeyError:
        print("El nodo con llave 3 no se encuentra en el árbol")
    tree.print()
    tree.delete(8)  # Borrando el 8 (raíz, ambos hijos)
    tree.print()
    tree.insert(100)
    tree.print()
Ejemplo n.º 50
0
from BinaryTree import BinaryTree

def next_node(root):
    current = root
    if current.right is not None:
        current = current.right
        while current.left is not None:
            current = current.left
        return current

    # Go up until we find a parent who this is the left subtree of
    while current.parent is not None:
        if current.parent.left is current:
            return current.parent
        current = current.parent


if __name__ == '__main__':
    root = BinaryTree(4)
    root.addleft(BinaryTree(2))
    root.left.addright(BinaryTree(3))
    root.left.addleft(BinaryTree(1))
    root.addright(BinaryTree(6))
    print('Expect 3:', next_node(root.left).data)
    print('Expect 4:', next_node(root.left.right).data)

    # Tree of one node
    root = BinaryTree(0)
    print('Expect None:', next_node(root))
Ejemplo n.º 51
0
    along the longest path) recursively
    """
    # Base case
    if root.left == None and root.right == None:
        return acc
    elif root.left != None and root.right != None: # Neither child is None
        return max(calc_height(root.left, acc+1),
                   calc_height(root.right, acc+1))
    elif root.left != None:                        # At least one child is None
        return calc_height(root.left, acc+1)
    else:
        return calc_height(root.right, acc+1)

def is_balanced(root):
    if root.left != None and root.right != None:
        return abs(calc_height(root.left) - calc_height(root.right)) <= 1
    elif root.left != None:
        return calc_height(root.left) <= 1
    elif root.right != None:
        return calc_height(root.right) <= 1
    else:
        return True

if __name__ == '__main__':
    root = BinaryTree(1)
    root.right, root.left = BinaryTree(2), BinaryTree(3)
    print(is_balanced(root))
    print('Unbalancing the tree...')
    root.right.right, root.right.right.right = BinaryTree(4), BinaryTree(5)
    print(is_balanced(root))
Ejemplo n.º 52
0
from TreeNode import TreeNode as Node
from BinaryTree import BinaryTree as Tree

complete_15_vals = [8,4,12,2,6,1,3,5,7,10,14,9,11,13,15]

tree = Tree()
for val in complete_15_vals:
	tree.insert(val)


print(tree.pre_order())
print(tree.in_order())
print(tree.post_order())
 def test_check_subtree_one_by_one(self):
     bst2 = BinaryTree()
     bst2.insert(7)
     bst2.insert(9)
     bst2.insert(6)
     self.assertTrue(check_subtree_one_by_one(self.bst1, bst2))
     bst3 = BinaryTree()
     bst3.insert(5)
     bst3.insert(3)
     bst3.insert(6)
     bst3.root.right.data = 4
     self.assertFalse(check_subtree_one_by_one(self.bst1, bst3))
Ejemplo n.º 54
0
node2 = BinaryTreeNode(5)
node3 = BinaryTreeNode(9)

node2.right = node3
node1.left = node2
root.left = node1

node4 = BinaryTreeNode(2)
node5 = BinaryTreeNode(7)
node6 = BinaryTreeNode(4)

node4.left = node5
node4.right = node6
root.right = node4

bt = BinaryTree(root)
print root.level_order()
"""
print 'height of the tree:', root.height()
print 'full nodes count :',findFullNodeCount(root)
print 'search :'
print get_branch(root,3)
print 'tree diameter:',get_diameter(root)
print 'branches sums:',get_branch_sums(root)
print 'has path sum:',has_path_sum(root,21)

lca_res = lca(root,node6,node3)
print 'lca between %d and %d is %s'% (node6.val,node3.val,lca_res)
"""
#print exterior_binary_tree(root)
Ejemplo n.º 55
0

def max_sum_helper(r, curr_sum, max_sum):
    if not r:
        return
    curr_sum += r.data
    if not r.left and not r.right:
        max_sum[0] = max(max_sum[0], curr_sum)
        return
    max_sum_helper(r.left, curr_sum, max_sum)
    max_sum_helper(r.right, curr_sum, max_sum)


if __name__ == "__main__":
    """ The tree is:
                     1
                   /   \ 
                 2      3
                / \    / \
               4   5  8   9
                  / \    / \
                 6   7  10  11
                /
               12
    """
    t = BinaryTree()
    pre_order = [1, 2, 4, 5, 6, 12, 7, 3, 8, 9, 10, 11]
    in_order = [4, 2, 12, 6, 5, 7, 1, 8, 3, 10, 9, 11]
    root = t.create_tree(pre_order, in_order)
    print path_max_sum(root)
Ejemplo n.º 56
0
from BinaryTree import BinaryTree

operations = []
operations_count = 0

with open('abce.in') as f:
    operations_count = int(f.readline())
    for index, line in enumerate(f.readlines()):
        operation_number, *operation_params = [int(number)  for number in line.split()]
        operations.append({'type': operation_number,  'params': operation_params})

tree = BinaryTree()

with open('abce.out', 'w') as g:
    for operation in operations:

        if operation['type'] == 1:
            tree.insert(*operation['params'])

        elif operation['type'] == 2:
            tree.delete(*operation['params'])

        elif operation['type'] == 3:
            current = tree.find(tree.root, *operation['params'])
            g.write('{}\n'.format('1' if current else '0'))

        elif operation['type'] == 4:
            g.write('{}\n'.format(tree.predecessor(*operation['params'])))

        elif operation['type'] == 5:
            g.write('{}\n'.format(tree.successor(*operation['params'])))
Ejemplo n.º 57
0
def main():
    
    """
    
    #Test de construction d'un ABR
    n10 = BinaryTree.BinaryNode(10)
    n9 = BinaryTree.BinaryNode(9)
    n8 = BinaryTree.BinaryNode(8, n9, n10)
    
    n7 = BinaryTree.BinaryNode(7)
    n6 = BinaryTree.BinaryNode(6)
    n5 = BinaryTree.BinaryNode(5, n6, n7)
    
    n4 = BinaryTree.BinaryNode(4, n5, n8)
    
    
    n110 = BinaryTree.BinaryNode(110)
    n19 = BinaryTree.BinaryNode(19)
    n18 = BinaryTree.BinaryNode(18, n19, n110)
    
    n17 = BinaryTree.BinaryNode(17)
    n16 = BinaryTree.BinaryNode(16)
    n15 = BinaryTree.BinaryNode(15, n16, n17)
    
    n14 = BinaryTree.BinaryNode(14, n15, n18)
    
    #We create the binary tree from all the binary nodes
    tree = BinaryTree.BinaryTree(0, n4, n14)
    """
    
    #Here we are making a Binary Search Tree (we will call them tree in the future) by ourself
    
    n0 = BinaryNode(0)
    n1 = BinaryNode(1, n0, None)
    n5 = BinaryNode(5)
    n3 = BinaryNode(3, n1, n5)
    
    n9 = BinaryNode(9)    
    
    tree = BinaryTree(6, n3, n9)
    
    
    #We display the tree
    tree.display()
    
    #List 
    theList = [5,3,6,9,1, 14, 15 ,18 ,12, 24, 87, 45, 14, 15, 25,26,27,28,29,30,31,32,32,34,35,36,37]
    
    #Check if a value exists in the given tree
    numberOfAttempts = 36
    for i in range(0, numberOfAttempts):
        print("Research of", i, "(The first value is the result and the second the number of iterations/recursions):")
        print("Binary tree research:", tree.exists(i))
        print("List research:", existsInList(theList, i))
        print(" ")
      
    #Then do some stats
    binaryTreeAverage = 0
    listAverage = 0 
    for i in range(0, numberOfAttempts):
        binaryTreeAverage += tree.exists(i)[1]
        listAverage += existsInList(theList, i)[1]
    
    print("The average for the Binary tree is :", binaryTreeAverage/numberOfAttempts) #Si on avait N valeurs la moyenne tendrait vers ln(N)
    print("The average for the List is :", listAverage/numberOfAttempts) #Si on avait N valeurs la moyenne tendrait vers N/2
    
    print("\n\n")
    
    #Now we are making a tree with a list
    newTree = BinaryNode.fromList(theList)
    newTree.display()
    
    newTree.addNode(100)
    newTree.addNode(84)
    newTree.addNode(85)
    newTree.addNode(86)
    newTree.addNode(44)
    newTree.display()
      
    #We balance a tree using the list made of the tree's values
    newTree2 = newTree.balance()
    newTree2.display()
from BinaryTree import BinaryTree 
from BTreeNode import BTreeNode
import math

#set up binary tree
#

node1 = BTreeNode(12,None, None)
node2 = BTreeNode(13,None, None)
node3 = BTreeNode(11,None, None)
node4 = BTreeNode(10,None, None)
 
tree = BinaryTree(node1)

tree.addNewNode(node2)
tree.addNewNode(node3)
tree.addNewNode(node4)

print 'Node Count ' + str(tree.nodeCount)
print 'Height ' + str(tree.getHeight())
print tree.findNodeAndParent(11, tree.rootNode)
list = tree.findNodeAndParent(11, tree.rootNode)

print 'Getting info out of the List'
print list[0].getInformation()
print list[1].getInformation()
print '=========================================='

tree.recursiveInOrderBinaryTreeLoop(tree.rootNode)

print '=========================================='
Ejemplo n.º 59
0
 def __init__(self):
     BinaryTree.__init__(self)
Ejemplo n.º 60
0
from BinaryTree import BinaryTree
bt = BinaryTree()
vals = [9, 5, 7, 2, 6, 10, 16, 1, 3, 8, 17]
root = None
for x in vals:
    root = bt.insert(root, x)

# print("PreOrder")
# bt.preOrder(root)
# print()
print("InOrder")
bt.inOrder(root)
print()
# print("PostOrder")
# bt.postOrder(root)
# print()
# bt.search(root, 31)
root = bt.delete(root, 5)
bt.inOrder(root)