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)
    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)
예제 #3
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 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
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
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 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
예제 #8
0
    def test_right_leaning_tree_BT(self):
        #   Testing a right leaning tree
        #
        #   1
        #       \
        #           2
        #               \
        #                   3
        #                       \
        #                           4
        #                               \
        #                                   5
        #                                       \
        #                                           6
        #                                               \
        #                                                   7
        #
        
        root = BinaryTree.Node(1) 
        root.right = BinaryTree.Node(2) 
        root.right.right = BinaryTree.Node(3) 
        root.right.right.right = BinaryTree.Node(4) 
        root.right.right.right.right = BinaryTree.Node(5) 
        root.right.right.right.right.right = BinaryTree.Node(6) 
        root.right.right.right.right.right.right = BinaryTree.Node(7) 

        self.assertEqual(BinaryTree.findLCA(root, 4, 5), 4, "Should be 4")
        self.assertEqual(BinaryTree.findLCA(root, 4, 6), 4, "Should be 4")
        self.assertEqual(BinaryTree.findLCA(root, 3, 4), 3, "Should be 3")

        self.assertEqual(BinaryTree.findLCA2(root, 4, 5), 4, "Should be 4")
        self.assertEqual(BinaryTree.findLCA2(root, 4, 6), 4, "Should be 4")
        self.assertEqual(BinaryTree.findLCA2(root, 3, 4), 3, "Should be 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()
            })
예제 #10
0
    def test_left_leaning_tree_BT(self):
        #   Testing a left leaning tree
        #
        #                                               1
        #                                           /
        #                                       2
        #                                   /
        #                               3
        #                           /
        #                       4
        #                   /
        #               5
        #           /
        #       6
        #   /
        # 7
        #

        root = BinaryTree.Node(1) 
        root.left = BinaryTree.Node(2) 
        root.left.left = BinaryTree.Node(3) 
        root.left.left.left = BinaryTree.Node(4) 
        root.left.left.left.left = BinaryTree.Node(5) 
        root.left.left.left.left.left = BinaryTree.Node(6) 
        root.left.left.left.left.left.left = BinaryTree.Node(7) 

        self.assertEqual(BinaryTree.findLCA(root, 4, 5), 4, "Should be 4")
        self.assertEqual(BinaryTree.findLCA(root, 4, 6), 4, "Should be 4")
        self.assertEqual(BinaryTree.findLCA(root, 3, 4), 3, "Should be 3")
        self.assertEqual(BinaryTree.findLCA(root, 2, 4), 2, "Should be 2")

        self.assertEqual(BinaryTree.findLCA2(root, 4, 5), 4, "Should be 4")
        self.assertEqual(BinaryTree.findLCA2(root, 4, 6), 4, "Should be 4")
        self.assertEqual(BinaryTree.findLCA2(root, 3, 4), 3, "Should be 3")
        self.assertEqual(BinaryTree.findLCA2(root, 2, 4), 2, "Should be 2")  
예제 #11
0
    def test_balanced_tree_BT(self):
        #   Testing a simple balanced binary tree
        #
        #               1
        #       |               |
        #       2               3
        #   |       |       |       |
        #   4       5       6       7
        #
        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) 

        self.assertEqual(BinaryTree.findLCA(root, 4, 5), 2, "Should be 2")
        self.assertEqual(BinaryTree.findLCA(root, 4, 6), 1, "Should be 1")
        self.assertEqual(BinaryTree.findLCA(root, 3, 4), 1, "Should be 1")
        self.assertEqual(BinaryTree.findLCA(root, 2, 4), 2, "Should be 2")

        self.assertEqual(BinaryTree.findLCA2(root, 4, 5), 2, "Should be 2")
        self.assertEqual(BinaryTree.findLCA2(root, 4, 6), 1, "Should be 1")
        self.assertEqual(BinaryTree.findLCA2(root, 3, 4), 1, "Should be 1")
        self.assertEqual(BinaryTree.findLCA2(root, 2, 4), 2, "Should be 2")
    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)
예제 #13
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
예제 #14
0
    def test_leaf_node_BT(self):
        #  Testing with a single leaf node and keys not in the tree
        self.assertEqual(BinaryTree.findLCA(BinaryTree.Node(1), 1, 1), 1, "Should be 1")
        self.assertEqual(BinaryTree.findLCA(BinaryTree.Node(1), 1, 5), -1, "Should be -1")
        self.assertEqual(BinaryTree.findLCA(BinaryTree.Node(1), -10, 6), -1, "Should be -1")

        self.assertEqual(BinaryTree.findLCA2(BinaryTree.Node(1), 1, 1), 1, "Should be 1")
        self.assertEqual(BinaryTree.findLCA2(BinaryTree.Node(1), 1, 5), -1, "Should be -1")
        self.assertEqual(BinaryTree.findLCA2(BinaryTree.Node(1), -10, 6), -1, "Should be -1")
예제 #15
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)
def create_tree_from_inorder_BFS(inorder, bfs):

    root = b_tree.Node(bfs[0])

    left, right = partition_inorder(inorder, root.data)

    #partition bfs is needed because using original bfs will contain
    #level order nodes from
    bfs_left, bfs_right = partition_bfs(left, right, bfs)

    if left:
        root.left = create_tree_from_inorder_BFS(left, bfs_left)
    else:
        root.left = None

    if right:
        root.right = create_tree_from_inorder_BFS(right, bfs_right)
    else:
        root.right = None

    return root
def create_full_tree_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)

        left = []
        right = []
        if len(preorder[idx:]) >= 2:
            #this means there exists, next node to current root in preorder
            #since tree is full, this next node is left child of root.

            left, right = partition_postorder_full_tree(
                postorder, preorder[idx + 1], root.data)

        print "left: ",
        print left

        print "right: ",
        print right

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

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

        return root
    def test(self):
        root = BinaryTree.Node(1)

        self.assertEqual(root.getLeftChild(), None)
        self.assertEqual(root.getRightChild(), None)
예제 #20
0
 def testFind(self):
     t = BinaryTree.Tree()
     t.add(7)
     node = BinaryTree.Node(7)
     self.assertEqual(t.find(7).Value(), node.Value())
예제 #21
0
            else:
                temp.right = curr  #creating a back link
                curr = curr.left
        else:
            print str(curr.data),
            curr = curr.right


def morris_traversal_preorder(root):
    pass


#driver program.
tree = b_tree.BinaryTree(20)
root = tree.root
root.left = b_tree.Node(10)
root.right = b_tree.Node(30)
root.left.left = b_tree.Node(5)
root.left.right = b_tree.Node(15)
root.left.right.left = b_tree.Node(11)

print "regular: ",
tree.InorderTraversal(root, [], True)

print
print "morris:  ",
morris_traversal_inorder(root)

print
tree = b_tree.BinaryTree(1)
root = tree.root
예제 #22
0
def findSubtreeAndOpt(lines):
    # still under construction
    # exhaust a small tree reconstruction
    i = 0
    while i < len(lines):
        line_header = get_line_header(lines)
        # constructing the Binary Tree
        N = BinaryTree.Node(lines[i][0])
        BT1 = BinaryTree.BT(N)
        findSubTree(lines, line_header, BT1, N)
        # generate dictionary of singly-used-variables
        singly_used_variables = single_used_variables(lines)
        # finding all the elements, with a limit
        elements = BT1.findTouchableElementsLimit(5, singly_used_variables)
        # original lines involved with the elements
        struct = BT1.touchableElementsStructureLimit(5, singly_used_variables)
        original_line = gendistinct.lineToCode(struct, len(elements))
        # substitute to be compatible with the lines
        substitution(original_line, lines)
        # find out all the variables that only used a single time if no such variables, skip
        one_time_variables = []
        for e in elements:
            if singly_used_variables[e] == 0:
                one_time_variables.append(e)
        if len(one_time_variables) == 0:
            i += 1
            continue

        # generate all possible structures of the binary tree
        alltrees = gendistinct.genStruct(len(elements))
        trees = []
        # looping through all the possible structures, try to optimise it
        for tree in alltrees:
            T = gendistinct.convertToTrees(tree, elements)
            for t in T:
                trees.append(t)
        # eliminate isomorphic trees
        gendistinct.convertDistinct(trees, elements)
        # find the best tree
        # criteria for best tree:
        best_tree = None
        best_XOR = 100
        for j in range(len(trees)):
            trees[j] = gendistinct.lineToCode(trees[j], len(elements))
            substitution(trees[j], lines)
            # if the tree is the original tree, skip it
            flag = 0
            for k in range(len(trees[j])):
                if set(trees[j][k][1:]) == set(original_line[k][1:]):
                    continue
                else:
                    flag = 1
                    break
            if flag == 0:
                continue

            XOR = XOR_count(trees[j], lines)
            saves = saving(trees[j], one_time_variables, lines)
            XOR = XOR - saves
            if best_XOR > XOR:
                best_XOR = XOR
                best_tree = trees[j]
        if best_XOR < 0:
            saves = saving(trees[j], one_time_variables, lines)
            replaceLines(original_line, best_tree, lines, one_time_variables)
            i -= 1
        i += 1
예제 #23
0
                    else:
                        nodes_at_dist_k_down(root.left, k - dr - 2)

                return 1 + dr

            #if n is not present in left or right subtree return -1
            return -1


if __name__ == "__main__":

    # example 1

    tree = b_tree.BinaryTree(20)
    root = tree.root
    root.left = b_tree.Node(8)
    root.right = b_tree.Node(22)
    root.left.left = b_tree.Node(4)
    root.left.right = b_tree.Node(12)
    root.left.right.left = b_tree.Node(10)
    root.left.right.right = b_tree.Node(14)

    print "All nodes at distance k in example 1: "
    t = 8  #target node with data
    k = 2  #find all nodes from t which are at distance k
    nodes_at_dist_k(root, t, k)
    print

    # example 2

    tree = b_tree.BinaryTree(2)
    if root1 is not None and root2 is not None:
        return root1.data == root2.data and \
               isMirror(root1.left, root2.right) and \
               isMirror(root1.right, root2.left)

    return False


if __name__ == "__main__":

    # example 1

    tree = b_tree.BinaryTree(2)
    root = tree.root
    root.left = b_tree.Node(2)
    root.right = b_tree.Node(2)
    root.left.left = b_tree.Node(3)
    root.left.right = b_tree.Node(4)
    root.right.left = b_tree.Node(4)
    root.right.right = b_tree.Node(3)

    print "Tree is a mirror : " + str(isMirror(root, root))

    # example 2

    tree = b_tree.BinaryTree(1)
    root = tree.root
    root.left = b_tree.Node(2)
    root.right = b_tree.Node(2)
    # root.left.left = b_tree.Node(3)
예제 #25
0
if __name__ == "__main__":
    # tree = b_tree.BinaryTree(1)
    # root = tree.root
    # root.left = b_tree.Node(2)
    # root.right = b_tree.Node(3)
    # root.left.left = b_tree.Node(4)
    # root.left.right = b_tree.Node(5)
    # root.right.left = b_tree.Node(6)
    # root.right.right = b_tree.Node(7)
    # root.left.left.right = b_tree.Node(8)
    # root.left.right.right = b_tree.Node(9)
    # root.left.right.right.right = b_tree.Node(10)

    tree = b_tree.BinaryTree(20)
    root = tree.root
    root.left = b_tree.Node(8)
    root.right = b_tree.Node(22)
    root.left.left = b_tree.Node(5)
    root.left.right = b_tree.Node(3)
    root.right.left = b_tree.Node(4)
    root.right.right = b_tree.Node(25)
    # root.left.left.right = b_tree.Node(8)
    root.left.right.left = b_tree.Node(10)
    root.left.right.right = b_tree.Node(14)

    print "Left View of Tree : ",
    left_view(root, set(), 0)
    print
    print "Right View of Tree : ",
    right_view(root, set(), 0)
    print
예제 #26
0
 def test_node_with_cycle_BT(self):
     # Testing a node that has its self as its child
     root = BinaryTree.Node(1)
     root.left = root
     root.right = root
예제 #27
0
 def test_null_node_BT(self):
     testNode = BinaryTree.Node(None)
     self.assertEqual(testNode.key,None, "Should be null")
        if head.nextt is None and head is not dll:
            head.nextt = dll
        if dll_next is not None and dll_next != dll:
            dll_next.set_prev(dll)
            dll.set_nextt(dll_next)

        return dll_next, head


if __name__ == "__main__":

    # example 1

    tree = b_tree.BinaryTree(10)
    root = tree.root
    root.left = b_tree.Node(12)
    root.right = b_tree.Node(15)
    root.left.left = b_tree.Node(25)
    root.left.right = b_tree.Node(30)
    root.right.left = b_tree.Node(36)

    head = BTToDLL(root)

    # print doubly linked list
    while head is not None:
        print str(head.data) + " ",
        head = head.nextt
    print

    # example 2
    # tree = b_tree.BinaryTree(1)
    def test(self):
        root = BinaryTree.Node(1)

        self.assertEqual(root.getTreeString(), "()1()")
        self.assertEqual(root.getKey(), 1)
예제 #30
0
import BinaryTree as b_tree
import sys


def isBST(root, minn, maxx):
    if not root:
        return True

    if root.data <= minn or root.data > maxx:
        return False

    return isBST(root.left, minn, root.data) and isBST(root.right, root.data,
                                                       maxx)


#driver program
#   20
#   /  \
#   10  30
#  /  \
# 5    25

tree = b_tree.BinaryTree(20)
root = tree.root
root.left = b_tree.Node(10)
root.right = b_tree.Node(30)
root.left.left = b_tree.Node(5)
root.left.right = b_tree.Node(25)

print isBST(root, sys.maxint * -1, sys.maxint)