def test_determine_node_to_add_to_smaller_value_one_left_child_exists(
         self):
     bt = BinaryTree()
     bt.root = Node(4)
     bt.root.left_child = Node(3)
     node_to_add_to = bt._determine_node_to_add_to(bt.root, 2)
     self.assertEqual(bt.root.left_child, node_to_add_to)
 def test_determine_node_to_add_to_larger_value_one_right_child_exists(
         self):
     bt = BinaryTree()
     bt.root = Node(4)
     bt.root.right_child = Node(8)
     node_to_add_to = bt._determine_node_to_add_to(bt.root, 5)
     self.assertEqual(bt.root.right_child, node_to_add_to)
 def test_left_or_right_child_equal_value(self):
     bt = BinaryTree()
     bt.root = Node(4)
     bt.root.left_child = Node(3)
     bt.root.right_child = Node(7)
     result = bt._left_or_right_child(bt.root, 4)
     self.assertEqual(bt.root.right_child, result)
 def test_structure(self):
     node = Node(data='one')
     second_node = Node(data='two')
     third_node = Node(data='three',left=node, right=second_node)
     assert third_node.data == 'three'
     assert third_node.left.data == 'one'
     assert third_node.right.data == 'two'
    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_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_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_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_node_remove_root_only_right_child(self):
     bt = BinaryTree()
     bt.root = Node(4)
     bt.root.right_child = Node(6)
     bt.count = 2
     bt.delete_node(4)
     self.assertEqual(6, bt.root.value)
     self.assertEqual(None, bt.root.left_child)
     self.assertEqual(None, bt.root.right_child)
     self.assertEqual(1, bt.count)
 def test_delete_node_remove_root_right_and_left_child(self):
     bt = BinaryTree()
     bt.root = Node(4)
     bt.root.left_child = Node(2)
     bt.root.right_child = Node(6)
     bt.root.right_child.right_child = Node(8)
     bt.count = 4
     bt.delete_node(4)
     self.assertEqual(6, bt.root.value)
     self.assertEqual(2, bt.root.left_child.value)
     self.assertEqual(8, bt.root.right_child.value)
     self.assertEqual(None, bt.root.right_child.right_child)
     self.assertEqual(3, bt.count)
Beispiel #11
0
def helper(start, end):
    if start >= end:
        return [None] if start > end else [Node(start)]
    res = []
    for i in range(start, end):
        left = helper(start, i)
        right = helper(i + 1, end)
        for j in left:
            for k in right:
                node = Node(i)
                node.left = j
                node.right = k
                res.append(node)
    return res
 def test_find_node(self):
     bt = BinaryTree()
     bt.root = Node(4)
     bt.root.left_child = Node(2)
     bt.root.right_child = Node(6)
     bt.root.left_child.right_child = Node(3)
     bt.root.right_child.left_child = Node(5)
     bt.root.right_child.right_child = Node(8)
     bt.root.right_child.right_child.left_child = Node(7)
     bt.root.right_child.right_child.right_child = Node(12)
     # test 1
     found_node, previous_node = bt.find_node(bt.root, None, 4)
     self.assertEqual(bt.root, found_node)
     self.assertEqual(None, previous_node)
     # test 2
     found_node, previous_node = bt.find_node(bt.root, None, 2)
     self.assertEqual(bt.root.left_child, found_node)
     self.assertEqual(bt.root, previous_node)
     # test 3
     found_node, previous_node = bt.find_node(bt.root, None, 12)
     self.assertEqual(bt.root.right_child.right_child.right_child,
                      found_node)
     self.assertEqual(bt.root.right_child.right_child, previous_node)
     # test 4:
     found_node, previous_node = bt.find_node(bt.root, None, 999)
     self.assertEqual(None, found_node)
     self.assertEqual(None, previous_node)
    def test_bt_lca(self):
        BT = Node(50)  #                50
        BT.insert(25)  #               /  \
        BT.insert(75)  #             25   75
        BT.insert(60)  #            / \   / \
        BT.insert(100)  #          20  30 60 100
        BT.insert(80)  #                    /
        BT.insert(20)  #                  80
        BT.insert(30)

        self.assertEqual(
            lowest_common_ancestor_BT(BT, BT.left, BT.right).data, 50)
        self.assertEqual(lowest_common_ancestor_BT(BT, BT, BT).data, 50)
        self.assertEqual(lowest_common_ancestor_BT(BT, BT, BT.right).data, 50)
        self.assertEqual(lowest_common_ancestor_BT(BT, BT.left, BT).data, 50)
        self.assertEqual(
            lowest_common_ancestor_BT(BT, BT.left.left, BT.left.right).data,
            25)
        self.assertEqual(
            lowest_common_ancestor_BT(BT, BT.right.left, BT.right.right).data,
            75)
        self.assertEqual(
            lowest_common_ancestor_BT(BT, BT.left.left, BT.right.right).data,
            50)
        self.assertEqual(
            lowest_common_ancestor_BT(BT, BT.right.left,
                                      BT.right.right.left).data, 75)
        self.assertEqual(
            lowest_common_ancestor_BT(BT, BT.left.right, BT.left.right).data,
            30)
def tree_creator(arr, parent=None):
    # if arr is empty
    if len(arr) == 0:
        return None

    node = Node(arr[0])
    node.parent = parent

    # if there is only one node in the array
    if len(arr) == 1:
        return node

    subArr = arr[1:]
    left = []
    right = []
    for i in range(len(subArr)):
        if subArr[i] < node.data:
            left.append(subArr[i])
        else:
            right = subArr[i:]
            break

    node.left = tree_creator(left, node)
    node.right = tree_creator(right, node)

    return node
def generate_huffman_tree(array):
    while len(array) > 1:
        array.sort(key=lambda array: array[0])
        first = array.pop(0)
        second = array.pop(0)
        node = Node(first[0] + second[0])
        if type(first[1]) is str:
            node.left = Node(first[1])
        else:
            node.left = first[1]
        if type(second[1]) is str:
            node.right = Node(second[1])
        else:
            node.right = second[1]
        array.append((first[0] + second[0], node))
    return array[0][1]
Beispiel #16
0
def list_to_binary(list):
    if len(list) == 0:
        return None
    if len(list) == 1:
        node = Node(list[0])
        return node
    else:
        center_index = math.floor(len(list) / 2)
        left_tree = list[:center_index]
        right_tree = list[center_index + 1:]
        node = Node(list[center_index])
        if len(left_tree) > 0:
            node.left = list_to_binary(left_tree)
        if len(right_tree) > 0:
            node.right = list_to_binary(right_tree)
        return node
Beispiel #17
0
 def prepost(pr, pr_s, pr_e, po, po_s, po_e, n):
     """
     :type pr:list
     :type pr_s:int
     :type pr_e:int
     :type po:list
     :type po_s:int
     :type po_e:int
     :type n:dict
     :param pr:
     :param pr_s:
     :param pr_e:
     :param po:
     :param po_s:
     :param po_e:
     :param n:
     :return:
     """
     if pr_s > pr_e or po_s > po_e:
         return None
     head = Node(pr[pr_s])
     index = n.get(pr[pr_s + 1])
     head.left = prepost(pr, pr_s + 1, pr_s + 1 + index - po_s, po, po_s,
                         index, n)
     head.right = prepost(pr, pr_s + 2 + index - po_s, po, index + 1,
                          po_e - 1, n)
     return head
Beispiel #18
0
 def preinf(p, ps, pe, i, ii, ie, n):
     """
     :type p:list
     :type ps:int
     :type pe:int
     :type i:list
     :type ii:int
     :type ie:int
     :type n:dict
     :param p:
     :param ps:
     :param pe:
     :param i:
     :param ii:
     :param ie:
     :param n:
     :return:
     """
     if ps > pe:
         return n
     head = Node(p[ps])
     index = n.get(p[ps])
     head.left = preinf(p, ps + 1, ps + index - ii, i, ii, index - 1, node)
     head.right = preinf(p, ps + index + 1 - ii, pe, i, index + 1, ie, node)
     return head
Beispiel #19
0
 def infpost(i, ii, ie, p, ps, pe, n):
     """
     :type i:list
     :type ii:int
     :type ie:int
     :type p:list
     :type ps:int
     :type pe:int
     :type n:dict
     :param i:
     :param ii:
     :param ie:
     :param p:
     :param ps:
     :param pe:
     :param n:
     :return:
     """
     if ii > ie or ps > pe:
         return n
     head = Node(p[pe])
     index = n.get(p[pe])
     head.left = infpost(i, ii, index - 1, p, ps, ps + index - 1 - ii, node)
     head.right = infpost(i, index + 1, ie, p, ps + index - ii, pe - 1,
                          node)
     return head
Beispiel #20
0
def gen_huffman_tree(arr):
    """生成霍夫曼树"""
    li = list()
    for v in arr:
        node = Node(v)
        li.append(node)
    while len(li) > 1:
        # 根据节点的权重值对节点进行排序
        li.sort(key=lambda n: n.data)
        # 取出前两个树构造新树
        n1 = li.pop(0)
        n2 = li.pop(0)
        new_node = Node(n1.data + n2.data)
        new_node.lchild = n1
        new_node.rchild = n2
        li.append(new_node)
    return BinaryTree(li.pop(0))
    def test_empy_binary_tree(self):
        self.assertEqual(lowest_common_ancestor_BT(None, None, None), None)

        BT = Node(None)
        self.assertEqual(lowest_common_ancestor_BT(BT, BT, BT), None)
        self.assertEqual(lowest_common_ancestor_BT(BT, None, None), None)
        self.assertEqual(lowest_common_ancestor_BT(None, BT, None), None)
        self.assertEqual(lowest_common_ancestor_BT(None, None, BT), None)
    def test_tree_insert_root(self):
        """
        This test makes sure that root is properly inserted.

        """
        self.root = Node(random.randint(0, 100), random.randint(0, 100))
        self.keys = [self.root.key]
        self.assertEqual(self.inorder(self.root, []), sorted(self.keys))
def helper(l, lo, hi):
    if lo > hi:
        return
    mid = (lo + hi) >> 1
    node = Node(l[mid])
    node.left_child = helper(l, lo, mid - 1)
    node.right_child = helper(l, mid + 1, hi)
    return node
Beispiel #24
0
    def insert(self, new_val):
        current = self.root

        while current:

            if new_val >= current.value:
                if not current.right:
                    current.right = Node(new_val)
                    return
               
                current = current.right

            else:
                if not current.left:
                    current.left = Node(new_val)
                    return 

                current = current.left
 def _insert_value(self, node, data):
     if node is None:
         node = Node(data)
     else:
         if data <= node.data:
             node.left = self._insert_value(node.left, data)
         else:
             node.right = self._insert_value(node.right, data)
     return node
    def recurse(i, j):
        if j - i == 0:
            return None

        mid = j // 2 + i // 2
        root = Node(val=vals[mid])
        root.left = recurse(i, mid)
        root.right = recurse(mid + 1, j)
        return root
Beispiel #27
0
def parse_token(tokens):
    """
    parse tokens from lexical_parse.py;
    1. trait tokens in "()" as a expression token;
    2. find the lowest operator;
    3. binary split tokens with lowest operator;
    4. process left tokens and right tokens
    :param tokens: token list, the toke could be number, operator, scope and expression
    :return: syntax binary tree
    """
    token_size = len(tokens)
    if token_size == 0:
        raise SyntaxError("empty token")
    elif token_size == 1:
        token = tokens[0]
        token_type = token.type
        token_value = token.value
        if token_type == TYPE_OPERATOR:
            raise SyntaxError("expression should be number or sub expression, but %s is an operator" % token_value)
        elif token_type == TYPE_SCOPE:
            raise SyntaxError("expression should be number or sub expression, but %s is a parentheses" % token_value)
        elif token_type == TYPE_NUM:
            return Node(token)
        else:
            # expression need to binary split
            tokens = token_value

    # token is a expression, split it with operator
    # split tokens with ()
    token_without_parentheses = _split_sub_expression(tokens)

    # find lowest operator
    lowest_priority_operator_index = _find_lowest_priority_operator(token_without_parentheses)
    if lowest_priority_operator_index == -1:
        raise SyntaxError("can not find operator")

    # split
    left_sub_tokens = token_without_parentheses[:lowest_priority_operator_index]
    right_sub_tokens = token_without_parentheses[lowest_priority_operator_index + 1:]
    node = Node(token_without_parentheses[lowest_priority_operator_index])
    node.left = parse_token(left_sub_tokens)
    node.right = parse_token(right_sub_tokens)
    return node
 def generate_node(node_str):
     """
     利用节点数据建立node
     :type node_str:str
     :param node_str:
     :return:
     """
     if node_str == "#":
         return None
     return Node(node_str)
Beispiel #29
0
    def __init__(self, source_code):
        # source code of the program
        self.__source_code = source_code
        # data structure for Identifiers table
        self.__identifiers_table = Node()
        # data structure for constants
        self.__constants_table = Node()
        # data structure for codification table
        self.__cod_table = {}
        # data structure for program internal form
        self.__PIF = []
        # name of output file for constants table
        self.__constants_table_out = file_name.split(".")[0] + "_const.txt"
        # name of output file for PIF
        self.__PIF_out = file_name.split(".")[0] + "_pif.txt"
        # name of output file for Symbol table
        self.__identifiers_table_out = file_name.split(".")[0] + "_identifier.txt"

        self.__populate_cod_table()
Beispiel #30
0
 def _insert_value(self, node, data):
     if node is None:
         node = Node(data)
     else:
         # 주어진 이진 트리에 무작위로 배치하기 위한 알고리즘
         random_case = randint(0, 10)
         if random_case >= randint(0, self.random_level):
             node.left = self._insert_value(node.left, data)
         else:
             node.right = self._insert_value(node.right, data)
     return node