def maxDepth(self, root):
     """
     :type root: TreeNode
     :rtype: int
     """
     tree = BinaryTree(root)
     return tree.maxDepth()
示例#2
0
def get_tree(model, fe, index):
	tree = model.trees[index]
	fnames =  model.Predictor.featureNames
	btree	= BinaryTree()
	node_idx = 0
	btree.root = get_tree_(node_idx, fe, tree, fnames, 1)
	return btree	
示例#3
0
def get_tree(model, fe, index):
    tree = model.Trees()[index]
    fnames = model.FeatureNames()
    btree = BinaryTree()
    node_idx = 0
    btree.root = get_tree_(node_idx, fe, tree, fnames, 1)
    return btree
示例#4
0
def main():

    node_1, node_2, node_3 = build_tree(nwk_file)

    #for sequence[0] to sequence[len], deduce
    for i in range(seq_len):
        deduceRoot(node_1, i)
        deduceRoot(node_2, i)
        deduceRoot(node_3, i)

    root_seq = []  # final result, root sequence
    for i in range(seq_len):
        root_seq.append(ternary_deduce(node_1.get_seq_i(i), node_2.get_seq_i(i), node_3.get_seq_i(i)))

    path = BinaryTree.reversed_path(node_1,root_seq) + BinaryTree.reversed_path(node_2,root_seq) + BinaryTree.reversed_path(node_3,root_seq)

    # output
    with open(out_file, 'w') as fcsv:
        writer = csv.writer(fcsv)
        writer.writerow(['path', 'depth', 'position', 'parent', 'child'])
        for i in range(len(path)):  # i- path No.
            for j in range(len(path[i])-1):  # j- depth of parent node, from root to leaf
                for k in range(len(path[i][j])):  # k-th character of alignment
                    if path[i][j][k] != path[i][j+1][k]:
                        writer.writerow([i, j, k, path[i][j][k], path[i][j+1][k]])
示例#5
0
def unique_bst_q2_helper(start, end):
    bsts = []
    if start > end:
        bsts.append(BinaryTree(None))
        return bsts
    # current root is i
    for i in range(start, end + 1):
        # generate all left_subtrees, will return a list of all possible left subtrees
        left_subtrees = unique_bst_q2_helper(start, i - 1)
        # generate all right_subtrees, will return a list of all possible right subtrees
        right_subtrees = unique_bst_q2_helper(i + 1, end)

        # for each left subtree and each right subtree
        for j in range(len(left_subtrees)):
            for k in range(len(right_subtrees)):
                # current root is i
                curr_root = TreeNode(i)
                # connect curr_root to left subtree's root and right subtree's root
                curr_root.left = left_subtrees[j].root
                curr_root.right = right_subtrees[k].root
                # create a new bst using curr_root as root
                curr_bst = BinaryTree(curr_root)
                # append to the result
                bsts.append(curr_bst)
    return bsts
示例#6
0
 def pathSum(self, root, sum):
     """
     :type root: TreeNode
     :type sum: int
     :rtype: List[List[int]]
     """
     tree = BinaryTree(root)
     return tree.pathSum(sum)
示例#7
0
 def test_insertion(self):
   b = BinaryTree(10)
   b.insert(8)
   b.insert(20)
   b.insert(22)
   b.insert(12)
   b.insert(1)
   b.DFPrint()
   self.assertEqual(b.getRightChild().val, 20)
示例#8
0
def createForest(fileInfo, uniqueArray):
    forest = list()
    for x in uniqueArray:
        leaf = BinaryTree(0, x)
        for y in fileInfo:
            if x == y:
                leaf.addWeight(1)
        forest.append(leaf)
    return forest
示例#9
0
def createForest(fileInfo,uniqueArray):
	forest = list()
	for x in uniqueArray:
		leaf = BinaryTree(0,x)
		for y in fileInfo:
			if x == y:
				leaf.addWeight(1)
		forest.append(leaf)
	return forest
    def test(self):
        root = BinaryTree.Node(1)
        a = BinaryTree.Node(2)
        b = BinaryTree.Node(3)

        root.insertLeft(a)
        root.insertRight(b)

        self.assertEqual(LCA.findLCA(root.getGraph(), 2, 2), 2)
        self.assertEqual(LCA.findLCA(root.getGraph(), 3, 3), 3)
示例#11
0
def findSubTree(lines, line_header, BT, root):
    LC = lines[line_header[root.value]][1]
    RC = lines[line_header[root.value]][2]
    l = BinaryTree.Node(LC)
    r = BinaryTree.Node(RC)
    root.LC = l
    root.RC = r
    BT.size += 2
    l.Parent = root
    r.Parent = root
    if 'x' not in LC:
        findSubTree(lines, line_header, BT, l)
    if 'x' not in RC:
        findSubTree(lines, line_header, BT, r)
    def test(self):
        root = BinaryTree.Node(1)
        a = BinaryTree.Node(2)
        b = BinaryTree.Node(3)

        root.insertLeft(a)
        root.insertRight(b)

        self.assertEqual(root.getTreeString(), "(()2())1(()3())")
        self.assertEqual(root.getKey(), 1)
        self.assertEqual(root.getLeftChild().getKey(), 2)
        self.assertEqual(root.getRightChild().getKey(), 3)
        self.assertEqual(root.getLeftChild().getParent().getKey(), 1)
        self.assertEqual(root.getRightChild().getParent().getKey(), 1)
示例#13
0
 def test_7(self):
   b= BinaryTree("Root")
   b.insertLeft("leftmost")
   b.insertRight("right")
   b.insertLeft("left")
   self.assertFalse(isLeaf(b))
   self.assertTrue(isLeaf(b.getRightChild()))
   b.DFPrint()
示例#14
0
def buildParseTree(fpexp):
    fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree

    for i in fplist:

        if i == '(':
            currentTree.insertLeftChild('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()

        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRightChild('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()

        elif i == ')':
            currentTree = pStack.pop()

        elif i not in ['+', '-', '*', '/', ')']:
            try:
                currentTree.setRootVal(int(i))
                currentTree = pStack.pop()

            except ValueError:
                raise ValueError("token '{}' is not a valid integer".format(i))

    return eTree
 def setUp(self) -> None:
     self.mock_tree = BinaryTree.Tree()
     self.mock_tree.insert(2)
     self.mock_tree.insert(6)
     self.mock_tree.insert(0)
     self.mock_tree.insert(7)
     self.mock_tree.insert(5)
示例#16
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
def create_BST_from_preorder_postorder(postorder, preorder):
    global idx
    if idx >= len(preorder):
        return None
    else:
        root = b_tree.Node(preorder[idx])

        # print "root: " + str(root.data)
        #find root in inorder (partition inorder around root)
        left, right = partition_postorder_BST(postorder, root.data)
        # print "left: ",
        # print left
        #
        # print "right: ",
        # print right

        if left:
            idx += 1
            root.left = create_BST_from_preorder_postorder(left, preorder)
        else:
            root.left = None

        if right:
            idx += 1
            root.right = create_BST_from_preorder_postorder(right, preorder)
        else:
            root.right = None

        return root
示例#18
0
def loadBinaryTree(words):
    tree = bt.BinaryTree()

    for key, word in words.items():
        tree.insert(word, compWords)

    return tree
def create_tree_from_inorder_postorder(inorder, postorder):
    global idx
    if idx < 0:
        return None
    else:
        root = b_tree.Node(postorder[idx])

        # print "root: " + str(root.data)
        #find root in inorder (partition inorder around root)
        left, right = partition_inorder(inorder, root.data)
        # print "left: ",
        # print left

        # print "right: ",
        # print right

        #Note the order is changed , we first process right tree, then left tree in case of processing postorder
        if right:
            idx -= 1
            root.right = create_tree_from_inorder_postorder(right, postorder)
        else:
            root.right = None

        if left:
            idx -= 1
            root.left = create_tree_from_inorder_postorder(left, postorder)
        else:
            root.left = None

        return root
def create_tree_from_inorder_preorder(inorder, preorder):
    global idx  #remember whenever we use a global index in recursion, there is simpler iterative approach possible
    if idx >= len(preorder):
        return None
    else:
        root = b_tree.Node(preorder[idx])

        # print "root: " + str(root.data)
        #find root in inorder (partition inorder around root)
        left, right = partition_inorder(inorder, root.data)
        # print "left: ",
        # print left

        # print "right: ",
        # print right

        if left:
            idx += 1
            root.left = create_tree_from_inorder_preorder(left, preorder)
        else:
            root.left = None

        if right:
            idx += 1
            root.right = create_tree_from_inorder_preorder(right, preorder)
        else:
            root.right = None

        return root
def buildParseTree(fpexp):
    """modified buildParsTree method to handle boolean operations"""
    fplist = tokenize(fpexp)
    #print(fplist)
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree
    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        #included and, or , not
        elif i not in ['+', '-', '*', '/', ')', 'and', 'or', 'not']:
            if i.isdigit():
                #"i" is a number
                currentTree.setRootVal(int(i))
            else:
                #"i" is not a number
                currentTree.setRootVal(i)
            parent = pStack.pop()
            currentTree = parent
        #included and, or, not
        elif i in ['+', '-', '*', '/', 'and', 'or', 'not']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError
    return eTree
示例#22
0
def main():
    # create an empty binary tree
    btree = BinaryTree()

    add = raw_input("Add an employee to the tree? >>")
    if add == 'yes' or add == 'y':
        firstName = raw_input("Please enter first name: ")
        lastName = raw_input("Please enter last name: ")
        hoursPerWeek = input("Please enter hours per week: ")
        payRate = input("Please enter pay rate: ")
        employee = Employee(firstName, lastName, hoursPerWeek, payRate)

        if btree.isEmpty == True:
            btree.setRootVal(employee)
            print firstName, "set as root."
        else:
def create_BST_from_preorder(preorder):
    global idx

    if idx >= len(preorder):
        return None
    else:

        #in any preorder first element is the root that tree
        #also it's guaranteed that preorder won't be empty since it's checked
        #for in if-else below before making recursive call.
        root = b_tree.Node(preorder[0])

        #preorder is partitioned in such way that, all elements between current value
        #and first higher value than current value are on left
        #eg. preorder = [10, 5, 1, 7, 40, 50]
        #when processing 10 , left = [5,1,7] and right=[40,50]
        left, right = partition_preorder_BST(preorder, root.data)

        print "left",
        print left

        print "right",
        print right

        if left:
            root.left = create_BST_from_preorder(left)
        else:
            root.left = None

        if right:
            root.right = create_BST_from_preorder(right)
        else:
            root.right = None

        return root
示例#24
0
def main():
    testNum = [2, 3, 5, 4, 9, 6, 4, 7, 8, 1, 7, 2, 3, 4, 7, 2, 3, 5, 6, 4, 5]
    goal = np.array([4, 6, 7])
    testArray = np.reshape(testNum, (7, 3))
    tree = bt.BinaryTree(3)
    makeTree(tree, testArray)

    findNode(tree, goal, len(goal))
示例#25
0
def minimalTree(array):
	'''
	:param array: sorted array with increasing integer values
	:return: BinaryTree with minimal height
	'''
	if len(array) == 0:
		return None

	length = len(array)
	mid = length/2
	left = array[:mid]
	right = array[mid+1:]

	tree = BinaryTree(array[mid])
	tree.leftChild = minimalTree(left)
	tree.rightChild = minimalTree(right)
	return tree
def tree_sort(a_list):
    start = time.time()
    r = BinaryTree.BinaryTree(a_list[0])
    for x in range(len(a_list)):
        if x > 0:
            r.insert(a_list[x])
    end = time.time()
    return end-start
    def test(self):
        root = BinaryTree.Node(1)
        a = BinaryTree.Node(2)
        b = BinaryTree.Node(3)
        c = BinaryTree.Node(4)
        d = BinaryTree.Node(5)
        e = BinaryTree.Node(6)
        f = BinaryTree.Node(7)

        root.insertLeft(a)
        root.insertRight(b)
        a.insertLeft(c)
        a.insertRight(d)
        b.insertLeft(e)
        b.insertRight(f)

        self.assertEqual(root.getTreeString(),
                         "((()4())2(()5()))1((()6())3(()7()))")
        self.assertEqual(root.getKey(), 1)
        self.assertEqual(root.getLeftChild().getKey(), 2)
        self.assertEqual(root.getRightChild().getKey(), 3)
        self.assertEqual(root.getLeftChild().getLeftChild().getKey(), 4)
        self.assertEqual(root.getLeftChild().getRightChild().getKey(), 5)
        self.assertEqual(root.getRightChild().getLeftChild().getKey(), 6)
        self.assertEqual(root.getRightChild().getRightChild().getKey(), 7)
        self.assertEqual(root.getLeftChild().getParent().getKey(), 1)
        self.assertEqual(root.getRightChild().getParent().getKey(), 1)
        self.assertEqual(
            root.getLeftChild().getLeftChild().getParent().getKey(), 2)
        self.assertEqual(
            root.getLeftChild().getRightChild().getParent().getKey(), 2)
        self.assertEqual(
            root.getRightChild().getLeftChild().getParent().getKey(), 3)
        self.assertEqual(
            root.getRightChild().getRightChild().getParent().getKey(), 3)
    def test(self):
        root = BinaryTree.Node(1)
        a = BinaryTree.Node(2)
        b = BinaryTree.Node(3)
        c = BinaryTree.Node(4)
        d = BinaryTree.Node(5)
        e = BinaryTree.Node(6)
        f = BinaryTree.Node(7)

        root.insertLeft(a)
        root.insertRight(b)
        a.insertLeft(c)
        a.insertRight(d)
        b.insertLeft(e)
        b.insertRight(f)

        self.assertEqual(
            root.getGraph(), {
                1: set([2, 3]),
                2: set([4, 5]),
                4: set(),
                5: set(),
                3: set([6, 7]),
                6: set(),
                7: set()
            })
示例#29
0
def build_tree(f):
    str_nwk = open(f).read().strip(';')  # Newick_110.nwk
    stack_nwk = []
    header = ''

    for i, c in enumerate(str_nwk):
        if c == ',':
            if header:  # end of header, push a leaf
                tmp_node = BinaryTree.BinaryTree(header)
                tmp_node.set_seq(list(search_align_file(header)))  # get sequence
                stack_nwk.append(tmp_node)
                header = ''
        elif c == ')':  # new blank node
            if i == len(str_nwk) - 1:  # the last ), left 3 nodes
                break

            if header:  # push a leaf
                tmp_node = BinaryTree.BinaryTree(header)
                tmp_node.set_seq(list(search_align_file(header)))  # get sequence
                stack_nwk.append(tmp_node)
                header = ''

            # if c.next == ';': break
            # print("before", stack_nwk)
            tmp_node = BinaryTree.BinaryTree(0)
            tmp_node.rightchild = stack_nwk.pop()
            tmp_node.leftchild = stack_nwk.pop()
            stack_nwk.pop()
            stack_nwk.append(tmp_node)
            # print("after",stack_nwk)

        elif c == '(':
            stack_nwk.append('(')

        else:  # header
            header += c

    # 3 nodes left in stack
    # deal with tree nodes
    node_1 = stack_nwk.pop()
    node_2 = stack_nwk.pop()
    node_3 = stack_nwk.pop()

    return node_1, node_2, node_3
示例#30
0
def buildHuffManTree(forest):
	while (len(forest)>1):
		# already sorted
		tempNode1 = forest[0]
		tempNode2 = forest[1]
		totalWeight = tempNode1.weight + tempNode2.weight
		innerNode = BinaryTree(totalWeight,'@') # inner node
		if (tempNode1.weight >= tempNode2.weight):
			tempNode1.code = "1"
			innerNode.right = tempNode1
			tempNode2.code =  "0"
			innerNode.left = tempNode2
		else:
			tempNode2.code = "1"
			innerNode.right = tempNode2
			tempNode1.code = "0"
			innerNode.left = tempNode1
		forest.append(innerNode)
		forest = forest[2:]
		forest = sortForest(forest)
	return forest
示例#31
0
    def __init__(self, frame, callback):
        # callback to send msgs back to caller
        self.callback = callback

        self.canvas = Canvas(frame, background="white", cursor="hand1")
        self.canvas.grid(row=0, column=0, sticky=NSEW)
        # insert horizontal scrollbar
        hscroll = Scrollbar(frame, orient=HORIZONTAL, command=self.canvas.xview)
        hscroll.grid(row=1, column=0, sticky=EW)
        self.canvas.configure(xscrollcommand=hscroll.set)

        self.selected = self.sel_rect = None
        self.tree = rbt.BinaryTree()
示例#32
0
def constructBinaryTree(l):
    counter = 0
    y = BinaryTree.Node(l)
    thislevel = [y]
    A = BinaryTree.BT(y)
    while len(thislevel) > 0:
        nextlevel = []
        for i in range(len(thislevel)):
            if type(thislevel[i].value) == list and len(thislevel[i].value) == 2:
                k = thislevel[i]
                k.LC = BinaryTree.Node(thislevel[i].value[0])
                k.RC = BinaryTree.Node(thislevel[i].value[1])
                A.size += 2
                k.value = "z"+str(counter)
                counter += 1
                k.LC.parent = k
                k.RC.parent = k
                nextlevel.append(k.LC)
                nextlevel.append(k.RC)
        thislevel = nextlevel
        
    return A
示例#33
0
def add(node, value):
    """Add a node on the root of BST"""
    if node is None:
        return BinaryTree.node(value)

    if node['value'] > value:
        node['left'] = add(node['left'], value)
        return node
    elif node['value'] < value:
        node['right'] = add(node['right'], value)
        return node
    else:
        return node
示例#34
0
 def test_null_tree_BT(self):
     #  Testing a null input
     self.assertEqual(BinaryTree.findLCA(None, 0, 0), -1, "Should be -1")
     self.assertEqual(BinaryTree.findLCA(None, 1, 5), -1, "Should be -1")
     self.assertEqual(BinaryTree.findLCA(None, -10, 6), -1, "Should be -1")
     
     self.assertEqual(BinaryTree.findLCA2(None, 0, 0), -1, "Should be -1")
     self.assertEqual(BinaryTree.findLCA2(None, 1, 5), -1, "Should be -1")
     self.assertEqual(BinaryTree.findLCA2(None, -10, 6), -1, "Should be -1")
示例#35
0
class main:
    datos = pd.read_csv("/Users/isabella/Documents/Segundo Semestre/Estructura de Datos y Algoritmos/Talleres/Códigos/Taller 10/personas-en-situacion-de-vulnerabilidad.csv")
    datosLimpios = datos.drop(["MI", "Agency", "Room", "Building"], axis = 1)
    arbol = bt.BinaryTree()

    for i in range(len(datosLimpios)):
        #print(datosLimpios["FirstName"].values[i], datosLimpios["LastName"].values[i], datosLimpios["PhoneNumber"].values[i])
        person = Persona(datosLimpios["FirstName"].values[i], datosLimpios["LastName"].values[i], datosLimpios["PhoneNumber"].values[i])
        arbol.insertar(person.data)
        
    arbol.borrar("wanda 301-504-7271 \n")    
    arbol.imprimir()
    print(arbol.buscar('vivian brooks 301-504-1758'))
    print(arbol.buscar('Isabella Montoya 314-816-6711'))
    print(arbol.dibujar())
 def insert(self, Item):
     """ Inserts an item in the binary search tree. """
     # Post:
     # The item will be added to the tree, regardless of whether the tree already contains an item with the same search key.
     if self.tree is None:
         self.tree = BinaryTree(Item)
     else:
         recordKey = self.key_map.map(Item)
         if recordKey < self.key:
             if self.tree.left is None:
                 self.tree.left = BinaryTree(Item)
             else:
                 self.left.insert(Item)
         elif self.tree.right is None:
             self.tree.right = BinaryTree(Item)
         else:
             self.right.insert(Item)
示例#37
0
 def start_test(self, type):
     results = np.zeros((50, 3))
     for index, i in enumerate(self.bases):
         # create
         if type == 0:
             tree = BinaryTree()
         elif type == 1:
             tree = AVLTree()
         elif type == 2:
             tree = Treap()
         elif type == 3:
             tree = SplayTree()
         for e in self.dataset[0:i]:
             tree.insert(e)
         results[index, :] = self.test_tree(tree, type)
     return results
示例#38
0
 def test_balanced_tree_common_parent_BT(self):
     #   Testing a simple balanced binary tree
     #
     #               1
     #       |               |
     #       2               3
     #   |       |       |       |
     #   4       5       6       7
     #       |               |
     #       8               9
     #
     root = BinaryTree.Node(1) 
     root.left = BinaryTree.Node(2) 
     root.right = BinaryTree.Node(3) 
     root.left.left = BinaryTree.Node(4) 
     root.left.right = BinaryTree.Node(5) 
     root.right.left = BinaryTree.Node(6) 
     root.right.right = BinaryTree.Node(7) 
     sharedNode1 = BinaryTree.Node(8)
     root.left.left.right = sharedNode1
     root.left.right.left = sharedNode1
     sharedNode2 = BinaryTree.Node(9)
     root.right.left.right = sharedNode2
     root.right.right.left = sharedNode2
    def test(self):
        root = BinaryTree.Node(1)
        a = BinaryTree.Node(2)
        b = BinaryTree.Node(3)
        c = BinaryTree.Node(4)
        d = BinaryTree.Node(5)
        e = BinaryTree.Node(6)
        f = BinaryTree.Node(7)

        root.insertLeft(a)
        root.insertRight(b)
        a.insertLeft(c)
        a.insertRight(d)
        b.insertLeft(e)
        b.insertRight(f)

        self.assertEqual(LCA.findLCA(root.getGraph(), 1, 8), -1)
        self.assertEqual(LCA.findLCA(b.getGraph(), 6, 4), -1)
class BinarySearchTree(ITree):
    """ Describes a binary search tree. """

    def __init__(self, KeyMap, tree = None):
        self.key_map = KeyMap
        self.tree = tree

    def traverse_inorder(self, Target = None):
        """ Performs inorder traversal on the binary search tree and writes its items to the given target collection. """
        # Post:
        # This method returns a read-only list with element type 'T' that can be used for iteration.
        if Target is None:
            aList = LinkedList()
            self.traverse_inorder(aList)
            return aList
        if self.tree is not None:
            self.tree.traverse_inorder(Target)

    def get_leftmost(self):
        """ Gets the binary tree's leftmost node.
            This method is private. """
        if self.tree is None:
            return None
        else:
            ltree = self.left
            if ltree.is_empty:
                return self
            else:
                return ltree.get_leftmost()

    def __iter__(self):
        """ Creates an iterator that iterates over every element in the tree. """
        rolist = self.traverse_inorder()
        i = 0
        while i < rolist.count:
            yield rolist[i]
            i += 1

    def insert(self, Item):
        """ Inserts an item in the binary search tree. """
        # Post:
        # The item will be added to the tree, regardless of whether the tree already contains an item with the same search key.
        if self.tree is None:
            self.tree = BinaryTree(Item)
        else:
            recordKey = self.key_map.map(Item)
            if recordKey < self.key:
                if self.tree.left is None:
                    self.tree.left = BinaryTree(Item)
                else:
                    self.left.insert(Item)
            elif self.tree.right is None:
                self.tree.right = BinaryTree(Item)
            else:
                self.right.insert(Item)

    def retrieve(self, Key):
        """ Retrieves the item with the specified key. """
        # Post:
        # If the binary search tree contains an item with the specified key, said item is returned.
        # If not, None is returned.
        if self.tree is None:
            return None
        elif Key == self.key:
            return self.tree.data
        elif Key < self.key:
            return self.left.retrieve(Key)
        else:
            return self.right.retrieve(Key)

    def remove(self, Key):
        """ Removes the item with the specified key from the binary search tree. """
        # Post:
        # If the search tree contains an item with the provided key, it is removed, and true is returned.
        # Otherwise, the tree's state remains unchanged, and false is returned.
        if self.is_empty:
            return False
        elif self.count == 1:
            if Key == self.key_map.map(self.tree.data):
                self.tree = None
                return True
            else:
                return False
        else:
            newTree = self.immutable_remove(Key)
            changed = not self.equals(newTree)
            self.tree.copy_from(newTree.tree)
            return changed

    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

    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

    def equals(self, Other):
        """ Compares two trees for equality.
            This method is not intended for general use, and was specifically created for the 'Remove(TKey)' method.
            It uses reference comparison to achieve O(log(n)) performance.
            This method is private. """
        if self.tree == Other.tree:
            return True
        elif self.is_empty or Other.is_empty:
            return self.is_empty == Other.is_empty
        else:
            if self.tree.data != Other.tree.data:
                return False
            return self.left.equals(Other.left) and self.right.equals(Other.right)

    @property
    def left(self):
        """ Gets the binary tree's left subtree. """
        if self.tree is None:
            return None
        else:
            return BinarySearchTree(self.key_map, self.tree.left)

    @left.setter
    def left(self, value):
        """ Sets the binary tree's left subtree.
            This accessor is private. """
        self.tree.left = value.tree

    @property
    def key_map(self):
        """ Gets the function that maps the binary search tree's records to their search keys. """
        return self.key_map_value

    @key_map.setter
    def key_map(self, value):
        """ Sets the function that maps the binary search tree's records to their search keys.
            This accessor is private. """
        self.key_map_value = value

    @property
    def is_empty(self):
        """ Gets a boolean value that indicates if the binary search tree is empty. """
        return self.tree is None

    @property
    def key(self):
        """ Gets the binary tree's root key. """
        if self.tree is None:
            return None
        else:
            return self.key_map.map(self.tree.data)

    @property
    def right(self):
        """ Gets the binary tree's right subtree. """
        if self.tree is None:
            return None
        else:
            return BinarySearchTree(self.key_map, self.tree.right)

    @right.setter
    def right(self, value):
        """ Sets the binary tree's right subtree.
            This accessor is private. """
        self.tree.right = value.tree

    @property
    def count(self):
        """ Gets the number of items in the binary search tree. """
        if self.tree is None:
            return 0
        else:
            return self.tree.count

    @property
    def is_leaf(self):
        """ Gets a boolean value that indicates if the binary search tree is either empty, or a leaf. """
        # Post:
        # Returns true if this binary search tree is empty or has no children.
        # Otherwise, returns false.
        return self.tree is None or self.tree.left is None and self.tree.right is None
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.max_depth(root) != -1

    def max_depth(self, root):
        if root is None:
            return 0

        left_depth = self.max_depth(root.left)
        right_depth = self.max_depth(root.right)

        if abs(left_depth - right_depth) > 1 or left_depth == -1 or right_depth == -1:
            return -1

        return max(left_depth, right_depth) + 1


# 用我自定义的Tree无法验证, 因为我是用None 代替"空", 但None也是一个节点.
import BinaryTree

testtree1 = BinaryTree.balanced_tree()
testtree1.print_tree()
print '1. is balanced?:\n', Solution().isBalanced(testtree1.root)

print '\n'
testtree2 = BinaryTree.not_balanced_tree()
testtree2.print_tree()
print '2. is balanced?:\n', Solution().isBalanced(testtree2.root)
示例#42
0
class BinaryTreeTest(unittest.TestCase):

  @classmethod
  def setUpClass(self):
    self.tree = BinaryTree('root')

  @classmethod  
  def tearUpClass(self):
    del self.tree

  def test_instance(self):
    self.assertIsInstance(
      self.tree,
      BinaryTree
    )

  def test_one_level_insert(self):
    self.tree.insertLeft('left')
    self.tree.insertRight('right')

    self.assertEqual(
      self.tree.getLeftChild().val, 'left')
    self.assertEqual(
      self.tree.getRightChild().val, 'right')

  def test_insertion(self):
    b = BinaryTree(10)
    b.insert(8)
    b.insert(20)
    b.insert(22)
    b.insert(12)
    b.insert(1)
    b.DFPrint()
    self.assertEqual(b.getRightChild().val, 20)

  def test_4(self):
    self.tree.setRootVal('newRoot')

    self.assertEqual(
      self.tree.getRootVal(), 'newRoot'
      ) 
    
  def test_7(self):
    b= BinaryTree("Root")
    b.insertLeft("leftmost")
    b.insertRight("right")
    b.insertLeft("left")
    self.assertFalse(isLeaf(b))
    self.assertTrue(isLeaf(b.getRightChild()))
    b.DFPrint()

  def test_isSubTree_depth_1(self):
    b = BinaryTree(20)
    b.insertLeft(15).insertLeft(9).insertLeft(2)
    b.insertRight(30)
    b.getLeftChild().getLeftChild().insertRight(11)
    b.getLeftChild().insertRight(18)

    t = BinaryTree(15)
    t.insertLeft(9)
    t.insertRight(18)

    self.assertTrue(hasSubTree(b,t))
示例#43
0
  def test_isSubTree_depth_1(self):
    b = BinaryTree(20)
    b.insertLeft(15).insertLeft(9).insertLeft(2)
    b.insertRight(30)
    b.getLeftChild().getLeftChild().insertRight(11)
    b.getLeftChild().insertRight(18)

    t = BinaryTree(15)
    t.insertLeft(9)
    t.insertRight(18)

    self.assertTrue(hasSubTree(b,t))
示例#44
0
 def setUpClass(self):
   self.tree = BinaryTree('root')
                if node.left is None and node.right is None:
                    # print depth, '<--'
                    return depth
                if node.left is not None:
                    queue.append(node.left)
                if node.right is not None:
                    queue.append(node.right)

            depth += 1

        return depth

    def min_depth_1(self, root):
        if root is None:
            return 0
        return self.get_depth(root)

    def get_depth(self, root):
        if root is None:
            return sys.maxint
        if root.left is None and root.right is None:
            return 1
        return 1 + min(self.get_depth(root.left), self.get_depth(root.right))


test_tree = BinaryTree.balanced_tree()
test_tree.print_tree()
print "the minimum Depth is: ", Solution().minDepth(test_tree.root)
print "the minimum Depth is: ", Solution().min_depth(test_tree.root)
print "the minimum Depth is: ", Solution().min_depth_1(test_tree.root)
示例#46
0
    sample = [49.0,878,0,0,0,0.0,0.0,0.5886524822695035,0.01007749837144013,8.330999649696521E-5,77.0,996278.0,0.0,0.0,0.0,0.0,0.0,0.512396694214876,0.010821347647939602,9.128211621391228E-5,59.0,679212.0,0.49122807017543857,0.008672298427140695,3.574100028848093E-5,23.0,783413.0,0.5102040816326531,0.009019589332074581,4.720320981826764E-5,20.0,529624.0,0.4883720930232558,0.009337527757216876,7.7720207253886E-5,17.0,270199.0,0.6428571428571429,0.013555787278415016,1.4896469536719798E-4,6.0,60416.0,0.0,0.0,0.0,0.0,0.0,0.5996236179722418,0.012829533477561435,2.827980251844456E-4,2446.0,9013499.0,0.5101328633647141,0.08962641512795905,0.001186184882235155,894498.0,7.72576866E8,0.3285774482822191,0.011157233471238438,8.021888050667894E-5,49685.0,6.22110401E8,0.6334291187739464,0.013352407868228135,2.89453324086701E-4,6446.0,2.2846515E7,0.5171102661596958,0.015564555125725339,2.9358938933407016E-4,124.0,463231.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,16412.0,98800.0,35145.0,57507.0,1029462.0,35032.0,0.9421257204128133,0.9631378854109096,0.9897149405529294,393344.0,1112266.0,179348.0,357812.0,2.8900747E7,417537.0,0.9238412642813727,0.9594590971008119,1.0573712690860235,3007430.0,9363723.0,1775980.0,3015886.0,2.2344258E8,4096332.0,0.926223621771286,0.9543387491555083,1.050103966891084,410.0,1612.0,274.0,276.0,30090.0,991.0,0.8785942492012779,0.8793650793650793,0.9036511156186613,6126.0,27810.0,7002.0,7237.0,410538.0,15473.0,0.9382368703108253,0.9396339088666753,1.1147477108903177]
else:
    sample = get_sample(sample_file)
    #print sample

#bst = pickle.load(open('result/relevanceModelXG.all', 'rb'))
#node_list = dump_txt(bst, 'result/text_model', feature_list)
node_list, tree_num = dump_txt(model_file_path)
node_map = {}
for elem in node_list:
    tree_id = elem[1]
    node_id = elem[2]
    node_map[str(tree_id)+'_'+str(node_id)]= elem 


btree = BinaryTree()



tree_id = 0
node_id = 0
node = Node()
node.attr = {'color' : 'white', 'shape':'box', 'label':'I am a little decision tree'}
btree.root = node
node.left = get_tree(tree_id, node_map[str(tree_id)+'_'+str(node_id)], feature_list, sample, 1)

if model_file == '':
    os.popen('rm -rf ../png/default')
    os.popen('mkdir ../png/default')      
    png_out = '../png/default'
else:
示例#47
0
from BinaryTree import *
from stack import *
from queue import *

bn = BinaryTree(60)
bn.insertRight(70)
bn.getRight().insertLeft(65)
bn.insertRight(75)
bn.insertLeft(50)
bn.insertLeft(40)
bn.getLeft().insertRight(45)

"""
             60
            /   \
           50    70
          /  \   / \
         40  45 65  75


"""

print preOrder(bn,result=[])

def binaryTreeMax(root):
	if root:
		root_val = root.data
		left = binaryTreeMax(root.left)
		right = binaryTreeMax(root.right)
		max = left if left > right else right
		if max > root_val :
print "Testing IntegerQueue"
while not intQueue.empty():
    print intQueue.get()


# Test IntegerStack
stack = IntegerStack()
for i in intList:
    stack.push(i)

print "Testing IntegerStack"
while stack.checkSize() > 0:
    print stack.pop()

# Test BinaryTree
tree = BinaryTree(0)
tree.add(1, 0)
tree.add(2, 0)
tree.add(3, 1)
tree.add(4, 1)
tree.add(5, 2)
tree.add(6, 2)
tree.add(7, 3)
tree.add(8, 3)
tree.add(9, 7)

print "Testing BinaryTree with 10 integers added"
tree._print()

tree.delete(9)
tree.delete(7)
'''
Created on 19. lip 2016.

@author: jk
'''
from BinaryTree import *
from Utils import *
from Reader import read_docx

###########################[WORD_FFREQUENCY_CALCULATOR]##############################

document_text = read_docx('../resources/Homer2.docx')
frequencyBST = BinaryTree()

for word in document_text.split():
    # print (normalizeWord(word))
    normalizedWord = normalizeWord(word).encode('utf-8').strip().upper()
    createAndInsertNode(frequencyBST, normalizedWord)    
    
print '========================[UNIQUE WORDS INORDER]======================\n'
inorder_string_list = frequencyBST.inorder_as_string().split()
print 'unique words found: ' + str(len(inorder_string_list))
print_as_table(inorder_string_list, False)

print '\n\n---------------------[WORDS BY FREQUENCY]------------------------'
inorder_with_frequency = frequencyBST.inorder_with_frequency([])
inorder_with_frequency.sort(key=lambda tup: tup[0], reverse=True)
print_as_table(inorder_with_frequency, True)
示例#50
0
           /   / \
          11  13  4
         /  \      \
        7    2      1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Q2:

'''


from BinaryTree import *

def has_path_sum(root, target):
    return has_path_sum_helper(root, target, 0)
        
def has_path_sum_helper(root, target, curr_sum):
    if not root:
        return False
    curr_sum += root.data
        
    if not root.left and not root.right and curr_sum == target:
        return True
    return has_path_sum_helper(root.left, target, curr_sum) or has_path_sum_helper(root.right, target, curr_sum)

if __name__=='__main__':
    t = BinaryTree()
    pre_order = [5,4,11,7,2,8,13,4,1]
    in_order = [7,11,2,4,5,13,8,4,1]
    t.create_tree(pre_order, in_order, 'pre_in')
    print has_path_sum(t.root, 22)
class Solution(object):
    '''
    题解1 - Recursive
    二叉树的题用递归的思想求解自然是最容易的,此题要求为交换左右子节点,
    故递归交换之即可。具体实现可分返回值为空或者二叉树节点两种情况,返回值
    为节点的情况理解起来相对不那么直观一些。
    '''

    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root is None:
            return

        temp_treenode = root.left
        root.left = root.right
        root.right = temp_treenode

        self.invertTree(root.left)
        self.invertTree(root.right)


testtree = BinaryTree.test_tree()
testtree.print_tree()
print '\n'

Solution().invertTree(testtree.root)
testtree.print_tree()
示例#52
0
from BinaryTree import *

#          F
#        /   \
#      B       G
#    /   \       \
#  A      D       I
#       /   \    /
#      C     E  H

a = BinaryTree('A')
b = BinaryTree('B')
c = BinaryTree('C')
d = BinaryTree('D')
e = BinaryTree('E')
f = BinaryTree('F')
g = BinaryTree('G')
h = BinaryTree('H')
i = BinaryTree('I')

f.left  = b
f.right = g
b.left  = a
b.right = d
d.left  = c
d.right = e
g.right = i
i.left  = h

depthFirstPreOrder(f)
print
'''
from BinaryTree import *
def binary_tree_upside_down(root):
    dummy_root = TreeNode(0)
    cousin = None
    while root:
        # record left and right
        left_child = root.left
        right_child = root.right
        # insert under dummy_root's right
        root.right = dummy_root.right
        dummy_root.right = root
        # connect left
        root.left = cousin
        # update cousin and root itself
        cousin = right_child
        root = left_child
    return dummy_root.right


if __name__=='__main__':
    t1 = BinaryTree()
    pre_order = [1,2,4,5,3]
    in_order =  [4,2,5,1,3]
    r1 = t1.create_tree(pre_order, in_order)
    r2 = binary_tree_upside_down(r1)
    t2 = BinaryTree()
    t2.clone_tree(r2)
    t2.pre_order_print(r2)
    print
    t2.in_order_print(r2)
示例#54
0
    else:
        return LCA_BST(root.right, node1, node2)

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]
    post_order=[4,12,6,7,5,2,8,10,11,9,3,1]
    root=t.create_tree(post_order, in_order, indicator='post_in')
    test_cases = [(root.left.left,root.left.right.right), 
                  (root.left.right,root.left.right.left.left),
                  (root.left.left, root.right.right.left)]
    '''test cases are (4,7), (5,12), (4,8)'''
    for test in test_cases:
        node1 = test[0]
        node2 = test[1]
        print lowestAncestor(node1, node2).data, LCA(root, node1, node2).data
    bst = BinaryTree()
    pre_bst = [90,50,20,70,60,80,100,110]
    in_bst = [20,50,60,70,80,90,100,110]