Пример #1
0
def test_perfect_tree():
    tree = BinaryTree(1,
        BinaryTree(2, None, None),
        BinaryTree(3, None, None)
    )
    assert tree.height() == 2
    assert tree.balanced()
Пример #2
0
def test_balanced_tree():
    tree = BinaryTree(1,
        None,
        BinaryTree(3, None, None)
    )
    assert tree.height() == 2
    assert tree.balanced()
Пример #3
0
def convert_ptb_to_tree(line):
    index = 0
    tree = None
    line = line.rstrip()
    while '((' in line:
        line = re.sub('\(\(', '( (', line)
    while '))' in line:
        line = re.sub('\)\)', ') )', line)

    stack = []
    parts = line.split()
    for p_i, p in enumerate(parts):
        # opening of a bracket, create a new node, take parent from top of stack
        if p[0] == '(':
            tag = p[1:]
            if tree is None:
                tree = BinaryTree(index, tag)
            else:
                add_descendant(tree, index, tag, stack[-1])
            # add the newly created node to the stack and increment the index
            stack.append(index)
            index += 1
        # otherwise, update the word of the node on top of the stack, and pop it
        elif p[-1] == ')':
            tag = p[:-1]
            if tag != '':
                tree.set_word(index-1, tag)
            stack.pop(-1)
        else:
            # deal with a couple of edge cases
            parts[p_i+1] = p + '_' + parts[p_i+1]
    return tree
Пример #4
0
def test_very_unbalanced_tree():
    tree = BinaryTree(1,
        None,
        BinaryTree(2,
            None,
            BinaryTree(3, None, None)
        )
    )
    assert tree.height() == 3
    assert not tree.balanced()
Пример #5
0
 def getActualTree(self):
     state = self._getState()
     if state.tree_view == State.BINARY_TREE:
         logic = BinaryTree()
         return logic.treeToJson(state.actual_user.active_binary_position)
     elif state.tree_view == State.UNILEVEL_TREE:
         logic = UnilevelTree()
         return logic.treeToJson(state.actual_user.active_unilevel_position)
     else:
         raise Controller.UnknownTreeView
Пример #6
0
def create_minimal_bst(li, start, end):
    if end < start:
        return None
    
    # get the middle element of the list
    middle = (start + end) / 2
    n = BinaryTree(li[middle])
    n.left = create_minimal_bst(li, start, middle-1)
    n.right = create_minimal_bst(li, middle+1, end)
    # root = BinaryTree(li[middle], create_minimal_bst(li, start, middle-1), create_minimal_bst(li, middle+1, end))
    return n
def construct_help(preorder, inorder):
    if not preorder and not inorder:
        return None
    root_value = preorder[0]
    root_index = inorder.index(root_value)
    root = BinaryTree(root_value)
    root.leftChild = construct_help(preorder[1: root_index  + 1], \
            inorder[: root_index])
    root.rightChild = construct_help(preorder[root_index + 1:], \
            inorder[root_index + 1:])

    return root
class BSTTest(unittest.TestCase):

    def setUp(self):
        self.bst = BinaryTree(bst=True)

        self.bst.insert(Node(3))
        self.bst.insert(Node(7))
        self.bst.insert(Node(1))
        self.bst.insert(Node(5))
        # self.bst.print_in_order()

    def test_is_valid(self):
        self.assertEqual(True, self.bst.is_valid())
def buildDecisionTree(sofar, todo):
    """
    @return: decision tree root which contains all references to other nodes
    """
    if len(todo) == 0:
        return BinaryTree(sofar)
    else:
        withElement = buildDecisionTree(sofar + [todo[0]], todo[1:])
        withoutElement = buildDecisionTree(sofar, todo[1:])
        here = BinaryTree(sofar)
        here.set_left_branch(withElement)
        here.set_right_branch(withoutElement)
        return here
def generate_factor(treeFile, columnFile, prior, cpd, domain):

    # Build the binary tree and find the interior nodes
	tree = BinaryTree()
	tree.parse_from_string(read_nh_file_into_single_line(treeFile))
	interior_nodes = []
	tree.assign_idx(interior_nodes, [0])


	animal_to_idx={}
	idx_to_animal={}
	factors=[]


	def build_prior_factor(idx):
		factor=Factor()
		factor.scope = [idx]
		factor.card = [len(domain)]
		factor.val = prior
		return factor
	def build_evolution_factor(i2,i1):
		factor=Factor()
		factor.scope = [i2,i1]
		factor.card = [len(domain),len(domain)]
		factor.val = cpd
		return factor


	def assign_index(TreeNode):
		animal_to_idx[TreeNode.data]=TreeNode.idx+1
		idx_to_animal[TreeNode.idx+1]=TreeNode.data
		if TreeNode.left!=None:
			f_e=build_evolution_factor(TreeNode.left.idx+1,TreeNode.idx+1)
			f_e.name = TreeNode.left.data+'<--'+TreeNode.data
			factors.append(f_e)
			assign_index(TreeNode.left)
		if TreeNode.right!=None:
			f_e=build_evolution_factor(TreeNode.right.idx+1,TreeNode.idx+1)
			f_e.name = TreeNode.right.data+'<--'+TreeNode.data
			factors.append(f_e)
			assign_index(TreeNode.right)

	f_p=build_prior_factor(tree.idx+1)
	f_p.name=tree.data
	factors.append(f_p)
	assign_index(tree)

	sequences = read_sequences(columnFile,animal_to_idx)
	domain_to_idx = {domain[i]: i for i in xrange(len(domain))}

	return sequences,tree,factors
    def setUp(self):
        self.bst = BinaryTree(bst=True)

        self.bst.insert(Node(3))
        self.bst.insert(Node(7))
        self.bst.insert(Node(1))
        self.bst.insert(Node(5))
 def test_basic_functionality(self):
     in_ordr = [1, 3, 16, 29, 14, 86, 4, 18, 69, 63, 141]
     pre_ordr = [4, 3, 1, 29, 16, 86, 14, 69, 18, 141, 63]
     post_order = [1, 16, 14, 86, 29, 3, 18, 63, 141, 69, 4]
     tr = BinaryTree.from_in_and_pre_order_traversal(in_ordr, pre_ordr)
     curr_pre_order = pre_order_non_recur(tr.root)
     self.assertEqual(curr_pre_order, pre_ordr)
Пример #13
0
 def test_generate_node_count_data3(self):
     in_ordr = [3, 4, 1, 2, 6, 8, 12, 13, 16, 21]
     pre_ordr = [3, 6, 4, 2, 1, 16, 12, 8, 13, 21]
     tr = BinaryTree.from_in_and_pre_order_traversal(in_ordr, pre_ordr)
     util_generate_node_count_data(tr.root)
     self.assertEqual(tr.root['node_count'], len(in_ordr))
     self.assertEqual(tr.root['right']['node_count'], len(in_ordr) - 1)
     self.assertEqual(tr.root['right']['right']['node_count'], 5)
Пример #14
0
class DBDB(object):
    """
    implements the python dictionary API using the concrete BinaryTree implementation
    """
    def __init__(self, f):
        self._storage = Storage(f)
        # Data stores tend to use more complex types of search trees such as
        # B-trees, B+ trees, and others to improve the performance.
        self._tree = BinaryTree(self._storage)

    def _assert_not_closed(self):
        if self._storage.closed:
            raise ValueError('Database closed!')

    def commit(self):
        self._assert_not_closed()
        self._tree.commit()

    def close(self):
        self._storage.close()

    def __getitem__(self, key):
        self._assert_not_closed()
        return self._tree.get(key)

    def __setitem__(self, key, value):
        self._assert_not_closed()
        return self._tree.set(key, value)

    def __delitem__(self, key):
        self._assert_not_closed()
        return self._tree.pop(key)

    def __contains__(self, key):
        try:
            self[key]
        except KeyError:
            return False
        else:
            return True

    def __len__(self):
        return len(self._tree)
Пример #15
0
 def test_build_binary_tree(self):
     in_ordr = [1, 3, 16, 29, 14, 86, 4, 18, 69, 63, 141]
     pre_ordr = [4, 3, 1, 29, 16, 86, 14, 69, 18, 141, 63]
     post_order = [1, 16, 14, 86, 29, 3, 18, 63, 141, 69, 4]
     tr = BinaryTree.from_in_and_pre_order_traversal(in_ordr, pre_ordr)
     print("printing post order -->")
     tr.printPostOrder()
     print("expected order -->")
     print("(" + " ".join(map(str, post_order)) + " )")
     self.assertEqual(5, tr.maxDepth())
Пример #16
0
 def __init__(self, problem, pop, total_size, parent=None, level=1, n=1):
   """
   Initialize a node for the tree
   :param problem: Instance of the problem
   :param pop: Population for the node # Make sure format is called on pop first
   :param total_size: Total number of points in the whole population
   :param parent: Parent of the node
   :param level: Level of the tree
   :param n: Represents cut in the node
   :return: Node
   """
   BinaryTree.__init__(self)
   self.problem = problem
   self._pop = pop
   self.level = level
   self.N = n
   self.total_size = total_size
   self._parent = parent
   self.east, self.west, self.c, self.x = None, None, None, None
   self.abort = False
    def test_basic_functionality(self):
        in_order = [16, 6, 108, -1, -3, 42, 3, 4, -6, 12, 36, 8]
        pre_order = [3, 6, 16, -3, -1, 108, 42, 12, 4, -6, 8, 36]
        tr = BinaryTree.from_in_and_pre_order_traversal(in_order, pre_order)
        tr.populate_parent()

        self.assertEquals(get_node_successor(tr.root['left'])['data'], 108)
        self.assertEquals(get_node_successor(tr.root['left']['left'])['data'], 6)
        self.assertEquals(get_node_successor(tr.root['right']['left'])['data'], -6)
        self.assertEquals(get_node_successor(tr.root['right']['right']), None)
        self.assertEquals(get_node_successor(tr.root['right']['right']['left'])['data'], 8)
        self.assertEquals(get_node_successor(tr.root['left']['right']['left'])['data'], -3)
        self.assertEquals(get_node_successor(tr.root['left']['right']['right'])['data'], 3)
Пример #18
0
    def test_print_lvl_order(self):
        in_ordr = [1, 3, 16, 29, 14, 86, 4, 18, 69, 63, 141]
        pre_ordr = [4, 3, 1, 29, 16, 86, 14, 69, 18, 141, 63]
        tr = BinaryTree.from_in_and_pre_order_traversal(in_ordr, pre_ordr)
        expected_out = '''
        4
        3 69
        1 29 18 141
        16 86 63
        14
        '''

        print_level_order_using_dfs(tr)
        print("expected out -->")
        print(expected_out)
Пример #19
0
class DBDB(object):
    '''
    defines a class (DBDB) which implements the Python dictionary API using the concrete BinaryTree implementation. This is how you'd use DBDB inside a Python program.
    '''
    def __init__(self, f):
        self._storage = Storage(f)
        self._tree = BinaryTree(self._storage)

    def _assert_not_closed(self):
        if self._storage.closed:
            raise ValueError('Database closed.')

    def __getitem__(self, key):
        self._assert_not_closed()
        return self._tree.get(key)

    def __setitem__(self, key, value):
        self._assert_not_closed()
        return self._tree.set(key, value)

    def __delitem__(self, key):
        self._assert_not_closed()
        return self._tree.pop(key)

    def __contains__(self, key):
        try:
            self[key]
        except KeyError:
            return False
        else:
            return True

    def close(self):
        self._storage.close()

    def commit(self):
        self._assert_not_closed()
        self._tree.commit()

    def __len__(self):
        return len(self._tree)

    def find_max(self):
        return self._tree.find_max()
Пример #20
0
            if current.left is None:
                print "{data} ".format(data=current.data),
                current = current.right
            else:
                predecessor = MorrisTraversal.find_predecessor(current)

                if predecessor.right is None:
                    print "{data} ".format(data=current.data),
                    predecessor.right = current
                    current = current.left
                else:
                    predecessor.right = None
                    current = current.right


if __name__ == '__main__':
    bt = BinaryTree()
    root = None
    root = bt.add_head(10, root)
    root = bt.add_head(50, root)
    root = bt.add_head(-10, root)
    root = bt.add_head(7, root)
    root = bt.add_head(9, root)
    root = bt.add_head(-20, root)
    root = bt.add_head(30, root)

    mt = MorrisTraversal()
    mt.inorder(root)
    print "\n",
    mt.preorder(root)
 def setup_method(self):
     self.binary_tree = BinaryTree()
Пример #22
0
from binary_tree import BinaryTree

a_node = BinaryTree('a')
a_node.insert_left('b')
a_node.insert_right('c')

b_node = a_node.left_child
b_node.insert_right('d')

c_node = a_node.right_child
c_node.insert_left('e')
c_node.insert_right('f')

d_node = b_node.right_child
e_node = c_node.left_child
f_node = c_node.right_child

a = a_node.value
b = b_node.value
c = c_node.value
d = d_node.value
e = e_node.value
f = f_node.value

print
print('---------------------------------------')
print
print("               |%s|" % (a))
print("             /     \\")
print("           |%s|     |%s|" % (b, c))
print("              \\   /   \\")
    q = Queue()
    q.enqueue(root)
    node = None
    count = 0
    while not q.isEmpty():
        node = q.dequeue()  # dequeue FIFO

        # leaves has no left and right so increment here
        # can also find number of full nodes with not None here
        if node.left is None and node.right is None:
            count += 1
        else:
            if node.left is not None:
                q.enqueue(node.left)

            if node.right is not None:
                q.enqueue(node.right)
    return count


if __name__ == '__main__':

    root = BinaryTree(1)
    root.insertLeft(2)
    root.insertRight(3)
    root.getLeft().insertLeft(4)
    root.getLeft().insertRight(5)
    root.getRight().insertLeft(6)
    root.getRight().insertRight(7)

    print(numberOfLeavesInBTusingLevelOrder(root))
Пример #24
0
def tree_bottom(node, leaves=None):
    if leaves is None:
        raise ValueError("Must pass a leaves_list")
    if not node.left and not node.right:
        leaves.append(node)
        return
    if node.left:
        tree_bottom(node.left, leaves)
    if node.right:
        tree_bottom(node.right, leaves)


# Tests:
from binary_tree import BinaryTree
a = BinaryTree("a")
b = BinaryTree("b")
c = BinaryTree("c")
d = BinaryTree("d")
e = BinaryTree("e")
f = BinaryTree("f")
g = BinaryTree("g")
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
c.right = g
ext = tree_exterior(a)
for node in ext:
    print node.value
Пример #25
0
 def test_set_tree(self):
     t = BinaryTree([2, 3, 4])
     t2 = BinaryTree()
     t2.set_tree(t.root())
     self.assertEqual(str(t), str(t2))
Пример #26
0
from binary_tree import BinaryTree, Node
#from nonrecursion import BinaryTree, Node
if __name__ == '__main__':
    t = BinaryTree() # 이진트리 객체 t 생성
    n1 = Node(100)   # 8개의 노드 생성
    n2 = Node(200)
    n3 = Node(300)    
    n4 = Node(400)    
    n5 = Node(500)    
    n6 = Node(600)
    n7 = Node(700)    
    n8 = Node(800)
    n1.left  = n2  # n1의 왼쪽 자식->  n2
    n1.right = n3  # n1의 오른쪽 자식-> n3
    n2.left  = n4  # n2의 왼쪽 자식->  n4
    n2.right = n5  # n2의 오른쪽 자식-> n5
    n3.left  = n6  # n3의 왼쪽 자식->  n6
    n3.right = n7  # n3의 오른쪽 자식-> n7
    n4.left  = n8  # n4의 왼쪽 자식->  n8       
    t.root = n1    # t의 루트노드를 n1으로
    print('트리 높이 =', t.height(t.root))
    print('전위순회:\t', end='')
    t.preorder(t.root)
    print('\n중위순회:\t', end='')
    t.inorder(t.root)
    print('\n후위순회:\t', end='')
    t.postorder(t.root)
    print('\n레벨순회:\t', end='')
    t.levelorder(t.root)
Пример #27
0
def buildParseTree(fpexp):
    node = BinaryTree(None)
    parents = Stack()

    for c in fpexp.split():
        if c == '(':
            # (: create left -> push current node to stack -> descending to left
            node.insertLeft(None)
            parents.push(node)
            node = node.getLeft()
        elif c == ')':
            # ): pop node from stack -> ascending to root
            if parents.isEmpty() is False:
                node = parents.pop()
        elif c in ['+', '-', '*', '/']:
            # operator: set value -> create right -> push current node to stack -> descending to right
            node.setRoot(c)
            node.insertRight(None)
            parents.push(node)
            node = node.getRight()
        else:
            # operand: number, set value -> pop node from stack -> ascending to root
            try:
                node.setRoot(int(c))
                node = parents.pop()
            except ValueError:
                raise ValueError(
                    "token '{}' is not a valid integer. ".format(c))

    return node
Пример #28
0
 def __init__(self, f):
     self._storage = Storage(f)
     self._tree = BinaryTree(self._storage)
Пример #29
0
            if current.left is None:
                print "{data} ".format(data=current.data),
                current = current.right
            else:
                predecessor = MorrisTraversal.find_predecessor(current)

                if predecessor.right is None:
                    print "{data} ".format(data=current.data),
                    predecessor.right = current
                    current = current.left
                else:
                    predecessor.right = None
                    current = current.right


if __name__ == '__main__':
    bt = BinaryTree()
    root = None
    root = bt.add_head(10, root)
    root = bt.add_head(50, root)
    root = bt.add_head(-10, root)
    root = bt.add_head(7, root)
    root = bt.add_head(9, root)
    root = bt.add_head(-20, root)
    root = bt.add_head(30, root)

    mt = MorrisTraversal()
    mt.inorder(root)
    print "\n",
    mt.preorder(root)
Пример #30
0
from binary_tree import BinaryTree

print("Test Node")
left = Node(5)
head = Node(9)
right = Node(13)

head.left = left
head.right = right

print(head)
print(head.left)
print(head.right)

print("Test Tree")
tree = BinaryTree(Node(9))
tree.add(Node(5))
tree.add(Node(13))

# print(tree.head)
# print(tree.head.left)
# print(tree.head.right)

tree.print_inorder(tree.head)
tree.print_pretty()
print(tree.find_parent(5))
print(tree.find_parent(9))
print(tree.find_parent(13))
print(tree.find_parent(20))

print(tree.find_max(tree.head))
Пример #31
0
 def test_BinaryTree_getroot(self):
     t = BinaryTree([1, 2])
     r = t.root()
     self.assertEqual(r.val, 1)
from binary_tree import BinaryTree
from binary_tree import BinTreeNode
bt = BinaryTree()

bt.insert(24)
bt.insert(2)
bt.insert(4)
bt.insert(180)
bt.insert(40)
bt.insert(34)
bt.insert(61)

print("in order: ")
bt.in_order_print()

print()

print("reverse order: ")
bt.reverse_order_print()
Пример #33
0
 def __init__(self):
     BinaryTree.__init__(self)
     self.color = None
    def test_init_content(self):

        bt = BinaryTree(1)

        self.assertFalse(bt.is_empty())
        self.assertEqual(bt.get_content(), 1)
 def setUp(self):
     in_ordr = [1, 3, 16, 29, 14, 86, 4, 18, 69, 63, 141]
     pre_ordr = [4, 3, 1, 29, 16, 86, 14, 69, 18, 141, 63]
     self.tr = BinaryTree.from_in_and_pre_order_traversal(in_ordr, pre_ordr)
     self.tr.populate_parent()
    def test_init_r_tree(self):
        r_bt = BinaryTree(2)
        bt = BinaryTree(1, right_tree=r_bt)

        self.assertFalse(bt.is_empty())
        self.assertEqual(bt.get_right_tree(), r_bt)
Пример #37
0
from binary_tree import BinaryTree

from datastructures.trees.binary_tree_traversal import BinaryTraversal

if __name__ == '__main__':
    tree = BinaryTree()
    tree.add(1)
    tree.add(2)
    tree.add(3)
    tree.add(4)
    tree.add(5)
    tree.add(6)
    tree.add(7)
    tree.add(8)
    tree.add(9)
    tree.add(10)
    tree.add(11)
    tree.add(12)
    tree.add(14)
    tree.add(15)
    tree.add(15)
    tree.add(17)
    tree.add(18)

    traversal = BinaryTraversal()
    print("Print level by Reverse Ordering")
    traversal.level_order(tree.root, reverse=True)
    print("\nPrint level by Natural Ordering")
    traversal.level_order(tree.root)
    print('\nHeight Of the Tree: ', traversal.height(tree.root))
    print("Deepest Node: ", traversal.deepest_by_level(tree.root))
    def test_init_l_tree(self):
        l_bt = BinaryTree(2)
        bt = BinaryTree(1, left_tree=l_bt)

        self.assertFalse(bt.is_empty())
        self.assertEqual(bt.get_left_tree(), l_bt)
Пример #39
0
            # If left node, check it is smaller
            if node.left.data < node.data:
                queue.add(node.left)
            else:
                return False
        if node.right:
            # If right node, check it is greater
            if node.right.data > node.data:
                queue.add(node.right)
            else:
                return False

    return True


root = BinaryTree()
root.data = 8
root.left = BinaryTree()
root.left.data = 4
root.right = BinaryTree()
root.right.data = 12
root.left.right = BinaryTree()
root.left.right.data = 6
root.right.left = BinaryTree()
root.right.left.data = 10
root.right.right = BinaryTree()
root.right.right.data = 14

#      8
#    /   \
#   4     12
    def test_init_none(self):
        bt = BinaryTree()

        self.assertTrue(bt.is_empty())
Пример #41
0
        Perform a pre-order traversal of the tree. If the current node at a horizontal distance of height
         is the first we’ve seen, insert it in the map. Otherwise, compare the node with the existing
         one in map and if the height of the new node is greater, update in the Map.
        *Analysis:
        - Time Complexity = O(n)
        - Space Complexity = O(n)
        """
        distance_map = dict()
        TreeViews.__bottom_view_util(root, 0, 1, distance_map)

        for k in sorted([i for i in distance_map.keys()]):
            print((distance_map[k])[1],  end='  ')


if __name__ == '__main__':
    bt = BinaryTree.from_list( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
    bt.btToBST()
    bt.pprint()
    print("Different views of binary tree")
    print('     Left view - ', end='  ')
    TreeViews.left_view(bt.get_root(), 1, [0])
    print()
    print('     Right view - ', end='  ')
    TreeViews.right_view(bt.get_root(), 1, [0])
    print()
    print('     Top view - ', end='  ')
    TreeViews.top_view(bt.get_root())
    print()
    print('     Bottom view - ', end='  ')
    TreeViews.bottom_view(bt.get_root())
Пример #42
0
from binary_tree import BinaryTree


if __name__ == '__main__':
    tree = BinaryTree()

    values = [5, 3, 2, 4, 7, 6, 8]

    #        5
    #      /   \
    #     3     7
    #    / \   / \
    #   2   4 6   8

    [tree.add(x) for x in values]

    print 'Input:',
    print ', '.join(str(x) for x in values)


    print '\nPrefixed.:',
    for node in tree.course_prefixed():
        print node.data,

    print
    print '\nInfixed..:',
    for node in tree.course_infixed():
        print node.data,

    print
    print '\nPostfixed:',
Пример #43
0
def main():
    grid = Grid(4, 4)
    BinaryTree.on(grid)
    print(grid)
class TestBinaryTree:
    def setup_method(self):
        self.binary_tree = BinaryTree()

    def test_lookup(self):
        root = Node(data='two')
        root.left = Node(data='one')
        root.right = Node(data='tww')

        assert self.binary_tree.lookup(node=root, data='one') is True
        assert self.binary_tree.lookup(node=root, data='two') is True
        assert self.binary_tree.lookup(node=root, data='tww') is True

    def test_lookup_not_found(self):
        with pytest.raises(ValueError):
            self.binary_tree.lookup(node=self.binary_tree.root, data='foo')

    def test_insert(self):
        root = self.binary_tree.root
        root = self.binary_tree.insert(node=root, data='foo')
        assert root.data == 'foo'

    def test_insert_multiple(self):
        root = self.binary_tree.root
        root = self.binary_tree.insert(node=root, data='b')
        root = self.binary_tree.insert(node=root, data='a')
        root = self.binary_tree.insert(node=root, data='c')

        assert root.data == 'b'
        assert root.left.data == 'a'
        assert root.right.data == 'c'

    def test_min_root(self):
        root = Node(data=1)

        assert self.binary_tree.min(node=root).data == 1

    def test_min_left(self):
        root = Node(data='b')
        root.left = Node(data='a')

        assert self.binary_tree.min(node=root).data == 'a'

    def test_min_empty(self):
        assert self.binary_tree.min(node=self.binary_tree.root) is None

    def test_max_root(self):
        root = Node(data='a')
        
        assert self.binary_tree.max(node=root).data == 'a'

    def test_max_right(self):
        root = Node(data='c')
        root.right = Node(data='d')

        assert self.binary_tree.max(node=root).data == 'd'

    def test_max_empty(self):
        assert self.binary_tree.max(node=self.binary_tree.root) is None

    def test_delete_root(self):
        root = Node(data='one')
        root = self.binary_tree.delete(node=root, data='one')
        assert root is None

    def test_delete_with_left(self):
        root = Node(data=3)
        root.left = Node(data=2)
        root.left.left = Node(data=1)

        root = self.binary_tree.delete(node=root, data=2)
        assert root.left.data == 1

    def test_delete_with_right(self):
        root = Node(data=3)
        root.left = Node(data=1)
        root.left.right = Node(data=2)

        root = self.binary_tree.delete(node=root, data=1)
        assert root.left.data == 2

    def test_delete_with_both_children(self):
        root = Node(data=4)
        root.left = Node(data=2)
        root.left.left = Node(data=1)
        root.left.right = Node(data=3)

        root = self.binary_tree.delete(node=root, data=2)
        assert root.left.data == 3
        assert root.left.left.data == 1

    def test_delete_not_found(self):
        with pytest.raises(ValueError):
            self.binary_tree.delete(node=self.binary_tree.root, data=1)

    def test_size_some(self):
        root = Node(data=4)
        root.left = Node(data=2)

        assert self.binary_tree.size(node=root) == 2

    def test_size_empty(self):
        assert self.binary_tree.size(node=self.binary_tree.root) == 0

    def test_floor_one(self):
        root = Node(data='one')
        assert self.binary_tree.floor(node=root, data='one').data == 'one'

    def test_floor_with_max_child(self):
        root = Node(data=3)
        root.left = Node(data=1)
        root.left.right = Node(data=2)

        assert self.binary_tree.floor(node=root, data=3).data == 2

    def test_floor_without_max_child(self):
        root = Node(data=3)
        root.left = Node(data=1)

        assert self.binary_tree.floor(node=root, data=3).data == 1

    def test_floor_not_found(self):
        with pytest.raises(ValueError):
            self.binary_tree.floor(node=self.binary_tree.root, data='one')

    def test_ceiling_one(self):
        root = Node(data='one')
        assert self.binary_tree.ceiling(node=root, data='one').data == 'one'

    def test_ceiling_with_min_child(self):
        root = Node(data=1)
        root.right = Node(data=3)
        root.right.left = Node(data=2)

        assert self.binary_tree.ceiling(node=root, data=1).data == 2

    def test_ceiling_without_min_child(self):
        root = Node(data=1)
        root.right = Node(data=3)

        assert self.binary_tree.ceiling(node=root, data=1).data == 3

    def test_ceiling_not_found(self):
        with pytest.raises(ValueError):
            self.binary_tree.ceiling(node=self.binary_tree.root, data='one')

    def test_rank_root(self):
        root = Node(data=4)
        root.left = Node(data=1)
        root.left.right = Node(data=3)

        assert self.binary_tree.rank(node=root, data=4) == 3

    def test_rank_right(self):
        root = Node(data=4)
        root.left = Node(data=1)
        root.left.right = Node(data=3)
        root.right = Node(data=6)
        root.right.left = Node(data=5)
        
        assert self.binary_tree.rank(node=root, data=6) == 5

    def test_rank_not_found(self):
        with pytest.raises(ValueError):
            self.binary_tree.rank(node=self.binary_tree.root, data=1)
Пример #45
0
        preorder(tree.get_left_child())
        preorder(tree.get_right_child())
        
def postorder(tree):
    if tree != None:
        postorder(tree.get_left_child())
        postorder(tree.get_right_child())
        print(tree.get_root_value(), end=' ')
        
def inorder(tree):
    if tree != None:
        inorder(tree.get_left_child())
        print(tree.get_root_value(), end=' ')
        inorder(tree.get_right_child())        
      
root = BinaryTree('a')
root.insert_left('b')
root.insert_right('c')
root.get_left_child().insert_left('d')
root.get_left_child().insert_right('e')
root.get_right_child().insert_left('f')
root.get_left_child().get_left_child().insert_left('g')
root.get_left_child().get_left_child().insert_right('h')

print("Preorder")
preorder(root)
print()
print("Postorder")
postorder(root)
print()
print("Inorder")
Пример #46
0
 def test_display_big(self):
     t = BinaryTree([1, 2, 3, '#', 4, '#', 6])
     serialize = '   1       \n  / \\    \n /   \\   \n 2   3   \n  \\   \\ \n  4   6 \n        \n'
     self.assertEqual(str(t), serialize)
@file: validate_binary_search_tree.py

@desc:  验证二叉查找树:

@hint: 多种方法: 1. 中序遍历树,看是否递增
                 2. 递归, 分别找到左右子树的最大,最小值左比较
                 3. 预定上下届, 递归判断,看否满足要求
"""

# 方法2:
from binary_tree import BinaryTree
import math


def validate_binary_search_tree(root):
    return is_validate(root, -math.inf, math.inf)


def is_validate(node, low, up):
    if node is None:
        return True
    if low >= node.data or up <= node.data:
        return False
    return is_validate(node.left_child, low, node.data) and is_validate(node.right_child, node.data, up)


if __name__ == '__main__':
    tree = BinaryTree()
    tree.create_bst()
    result = validate_binary_search_tree(tree.root)
    print(result)
Пример #48
0
    def create_expression_tree(self):
        """ Cria uma arvore binaria a partir da expressao posfixa """

        if len(self.postfix_expression) == 1:
            self.expression_tree = BinaryTree(self.postfix_expression[0])
            return

        stack = []
        for value in self.postfix_expression:

            if value in '.+':

                right = stack.pop()
                left = stack.pop()
                bin_tree = BinaryTree(value)
                bin_tree.set_left_child(left)
                bin_tree.set_right_child(right)
                stack.append(bin_tree)

            elif value == '*':

                right = stack.pop()
                bin_tree = BinaryTree(value)
                bin_tree.set_right_child(right)
                stack.append(bin_tree)

            else:
                stack.append(value)

        self.expression_tree = stack[0]
        self.expression_tree.print_treeview()
Пример #49
0
 def placePosition(self, rootPosition):
     logic = BinaryTree()
     logic.placeNode(rootPosition, self)
     return logic.isMatrixFull(logic.getMatrixTop(self))
Пример #50
0
class RegularExpression(object):
    """ Implementa uma expressao regular """
    def __init__(self, expression):

        self.expression = expression.replace(' ', '')
        self.counter = 0
        if self.expression == "":
            raise ValueError("Expressao Vazia")
        self.postfix_expression = self.infix_to_postfix()
        self.expression_tree = None
        self.create_expression_tree()

    def create_state(self):
        """ Cria um estado baseado no counter da classe """

        state = 'Q' + str(self.counter)
        self.counter += 1
        return state

    def infix_to_postfix(self):
        """ Converte uma expressao infixa para uma posfixa """
        stack = []
        postfix = []
        previous = False

        for element in self.expression:
            if element == '(':
                previous = False
                stack.append(element)

            elif element == ')':
                previous = False
                while True:
                    stack_value = stack.pop()
                    if stack_value == '(':
                        break
                    postfix.append(stack_value)

            elif element in '.+*':
                previous = False
                while stack != [] and PREC[element] <= PREC[stack[-1]]:
                    postfix.append(stack.pop())
                stack.append(element)

            else:
                if previous:
                    while stack != [] and PREC['.'] <= PREC[stack[-1]]:
                        postfix.append(stack.pop())
                    stack.append('.')
                    postfix.append(element)
                    previous = True
                else:
                    postfix.append(element)
                    previous = True

        while stack != []:
            postfix.append(stack.pop())

        # print(f"Postfix is {postfix}")
        return postfix

    def union_to_automaton(self, first_aut, second_aut):
        """ Converte uma expressao de uniao em seu respectivo automato """

        final_state = self.create_state()
        finals = {final_state}
        initial = self.create_state()
        states = first_aut.states.union(second_aut.states).union(
            {initial, final_state})
        alphabet = first_aut.alphabet.union(second_aut.alphabet)

        resulting_function = {}
        resulting_function.update(first_aut.function)
        resulting_function.update(second_aut.function)

        resulting_function[initial] = {
            '&': {initial, first_aut.initial, second_aut.initial}
        }
        resulting_function[final_state] = {'&': finals}

        for final in first_aut.finals.union(second_aut.finals):
            resulting_function[final]['&'].add(final_state)

        # print(f"resulting_function = {resulting_function}")

        return Automaton(states, alphabet, resulting_function, finals, initial)

    def closure_to_automaton(self, automaton):
        """ Converte o fechamento para um automato """

        final_state = self.create_state()
        finals = {final_state}
        initial = self.create_state()
        states = automaton.states.union({initial, final_state})
        alphabet = automaton.alphabet

        resulting_function = {}
        resulting_function.update(automaton.function)

        resulting_function[initial] = {
            '&': {initial, automaton.initial, final_state}
        }
        resulting_function[final_state] = {'&': finals}

        finals_copy = automaton.finals.copy()
        for final in finals_copy:
            resulting_function[final]['&'].add(automaton.initial)
            resulting_function[final]['&'].add(final_state)

        # print(f"resulting_function = {resulting_function}")

        return Automaton(states, alphabet, resulting_function, finals, initial)

    def concatenation_to_automaton(self, first_aut, second_aut):  #pylint: disable=R0201
        """ Converte uma expressao de concatenacao em seu respectivo automato """

        states = first_aut.states.union(second_aut.states)
        finals = second_aut.finals
        initial = first_aut.initial
        alphabet = first_aut.alphabet.union(second_aut.alphabet)

        resulting_function = {}
        resulting_function.update(first_aut.function)
        resulting_function.update(second_aut.function)

        finals_copy = first_aut.finals.copy()
        for final in finals_copy:
            resulting_function[final]['&'].add(second_aut.initial)

        return Automaton(states, alphabet, resulting_function, finals, initial)

    def create_expression_tree(self):
        """ Cria uma arvore binaria a partir da expressao posfixa """

        if len(self.postfix_expression) == 1:
            self.expression_tree = BinaryTree(self.postfix_expression[0])
            return

        stack = []
        for value in self.postfix_expression:

            if value in '.+':

                right = stack.pop()
                left = stack.pop()
                bin_tree = BinaryTree(value)
                bin_tree.set_left_child(left)
                bin_tree.set_right_child(right)
                stack.append(bin_tree)

            elif value == '*':

                right = stack.pop()
                bin_tree = BinaryTree(value)
                bin_tree.set_right_child(right)
                stack.append(bin_tree)

            else:
                stack.append(value)

        self.expression_tree = stack[0]
        self.expression_tree.print_treeview()

    def create_automaton(self, current_node=None):
        """ Cria o automato que corresponde a expressao """

        if current_node is None:
            current_node = self.expression_tree

        # print(f"Current node is {current_node.get_value()}")

        if current_node.get_left_child(
        ) is None and current_node.get_right_child() is None:
            state = self.create_state()
            final = self.create_state()
            function = {
                state: {
                    '&': {state},
                    current_node.get_value(): {final}
                },
                final: {
                    '&': {final}
                }
            }
            aut = Automaton({state, final}, {current_node.get_value()},
                            function, {final}, state)
            return aut

        if current_node.get_left_child() is not None:
            left_aut = self.create_automaton(current_node.get_left_child())
        if current_node.get_right_child() is not None:
            right_aut = self.create_automaton(current_node.get_right_child())

        if current_node.get_value() == '.':
            return self.concatenation_to_automaton(left_aut, right_aut)

        if current_node.get_value() == '+':
            return self.union_to_automaton(left_aut, right_aut)

        # O valor eh *
        if current_node.get_left_child() is not None:
            return self.closure_to_automaton(left_aut)
        return self.closure_to_automaton(right_aut)
Пример #51
0
from binary_tree import BinaryTree

def bfs(tree, val):
    """
    Returns whether a node is present in a tree using breadth-first search
    """
    deque = deque([tree.root])
    while deque:
        current = deque.popleft()
        if current.data == val:
            return True
        else:
            if current.left:
                deque.append(current.left)
            if current.right:
                deque.append(current.right)

    return False

if __name__ == '__main__':
    b = BinaryTree.factory(1)
    b.insert(2)
    b.insert(3)

    assert bfs(b, 1) is True
    assert bfs(b, 3) is True
    assert bfs(b, 4) is False

    print 'All tests pass!'
Пример #52
0
def balanced_tree(ordered):
    bt = BinaryTree()
    add_range(bt, ordered, 0, len(ordered) - 1)
    return bt
from binary_tree import BinaryTree

def find_path(root_node, expected_sum):
    if not root_node:
        return
    path_list = []
    current_sum = 0
    find_path_help(root_node, expected_sum, path_list, current_sum)

def find_path_help(root_node, expected_sum, path_list, current_sum):
    current_sum += root_node.key
    path_list.append(root_node.key)
    is_leaf = not root_node.leftChild and not root_node.rightChild
    if is_leaf and current_sum == expected_sum:
        print path_list
    elif root_node.leftChild:
        find_path_help(root_node.leftChild, expected_sum, path_list, current_sum)
    elif root_node.rightChild:
        find_path_help(root_node.rightChild, expected_sum, path_list, current_sum)
    path_list.pop()

if __name__ == "__main__":
    my_binary_tree = BinaryTree(1)
    my_binary_tree.insertLeft(2)
    my_binary_tree.insertRight(3)
    my_binary_tree.insertLeft(4)
    my_binary_tree.pre_order()

    find_path(my_binary_tree, 7)
Пример #54
0
 def test_display(self):
     t = BinaryTree([1, 2, 3])
     serialize = ' 1   \n/ \\ \n2 3 \n    \n'
     self.assertEqual(str(t), serialize)
Пример #55
0
 def test_get_kth_node_in_order3(self):
     in_ordr = [3, 4, 1, 2, 6, 8, 12, 13, 16, 21]
     pre_ordr = [3, 6, 4, 2, 1, 16, 12, 8, 13, 21]
     tr = BinaryTree.from_in_and_pre_order_traversal(in_ordr, pre_ordr)
     util_generate_node_count_data(tr.root)
     self._test_kth_in_order(in_ordr, tr.root)
		return operators[x]
	else:
		return False

node1 = Node(12, None, None)
node2 = Node('+', None, None)
node3 = Node('*', None, None)
node4 = Node(10, None, None)
node5 = Node('-', None, None)
node6 = Node('/', None, None)
node7 = Node(7, None, None)
node8 = Node(20, None, None)
node9 = Node(2, None, None)

node2.left = node1
node2.right = node3
node3.left = node4
node3.right = node5
node5.left = node6
node5.right = node7
node6.left = node8
node6.right = node9

tree = BinaryTree(node2)


expression = tree.show_expression(tree.root)
print(expression)

print(tree.calculate_expression(expression))
Пример #57
0
import sys
sys.path.append('..')

from binary_tree import BinaryTree
from binary_tree import Node

# Set up tree
tree = BinaryTree(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)

# Test search
# Should be True
assert (tree.search(4) == True), "Failed in tree.search"
# Should be False
assert (tree.search(6) == False), "Failed in tree.search"

# Test print_tree
# Should be 1-2-4-5-3
assert (tree.print_tree() == "1-2-4-5-3"), "Failed in print_tree"

print ("ALL TEST PASSED")
Пример #58
0
 def test_height(self):
     t = BinaryTree([1, 2, 3, 4, 5])
     self.assertEqual(t.height(), 3)
Пример #59
0
from Queue import Queue

from binary_tree import BinaryTree

def bst(binary_tree):
    queue = Queue()
    queue.put(binary_tree.root)

    while(not queue.empty()):
        element = queue.get()
        print element.data
        if element.left is not None:
            queue.put(element.left)
        if element.right is not None:
            queue.put(element.right)


if __name__ == '__main__':
    """ Successfull Case """
    binary_tree = BinaryTree()
    for value in [5, 2, 1, 9, 10, 0, 6]:
        binary_tree.insert(value)

    bst(binary_tree)
Пример #60
0
from binary_tree import BinaryTree, Node
if __name__ == '__main__':
    t = BinaryTree()
    n1 = Node(100)
    n2 = Node(200)
    n3 = Node(300)
    n4 = Node(400)
    n5 = Node(500)
    n6 = Node(600)
    n7 = Node(700)
    n8 = Node(800)
    n1.left = n2
    n1.right = n3
    n2.left = n4
    n2.right = n5
    n3.left = n6
    n3.right = n7
    n4.left = n8
    t.root = n1
    print('Height =', t.height(t.root))
    print('Pre-order Traverse:\t', end='')
    t.preorder(t.root)
    print('\nIn-order Traverse:\t', end='')
    t.inorder(t.root)
    print('\nPost-order Traverse:\t', end='')
    t.postorder(t.root)
    print('\nLevel-order Traverse:\t', end='')
    t.levelorder(t.root)