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_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_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)
Exemple #4
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
 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)
Exemple #6
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
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
Exemple #8
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
 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 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
 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
 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)
Exemple #14
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
def neighborhood_k(index, points, K):
    root = None
    for q,i in zip(G._vertex, range(len(G._vertex))):
        node_data = NodeData(euc_dist(points[index], q), i)
        if root is not None:
            root.insert(node_data)
        else:
            root = Node(node_data)
    neighborhood_vertex = []
    root.SortedUntil(K, neighborhood_vertex)
    neighborhood_vertex = list(map(lambda x: x.data, neighborhood_vertex))
    return neighborhood_vertex
def plus_one(head):
    h = Node(0)
    h.next = head
    cur = h
    while cur.next is not None and cur.next.value != 9:
        cur = cur.next
    cur.value += 1
    cur = cur.next
    while cur is not None:
        cur.value = 0
        cur = cur.next
    return h.next if h.value == 0 else h
    def test_binary_tree(self):
        BT = Node(10)  #           10
        BT.insert(5)  #          / \
        BT.insert(15)  #         5   15
        self.assertEqual(BT.data, 10)  #
        self.assertEqual(BT.left.data, 5)  #
        self.assertEqual(BT.right.data, 15)  #

        BT.insert(25)
        BT.insert(2)
        self.assertEqual(BT.left.left.data, 2)
        self.assertEqual(BT.right.right.data, 25)
 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)
Exemple #19
0
 def clone(head):
     """
     克隆头节点
     :type head:Node
     :param head:
     :return:
     """
     if head is None:
         return head
     res = Node(head.value)
     res.left = clone(head.left)
     res.right = clone(head.right)
     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)
Exemple #21
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
Exemple #22
0
 def rebuild(value, start, end):
     if start > end:
         return None
     head = Node(value[end])
     little_end = 0
     large_start = end
     for i in range(start, end + 1):
         if value[i] < value[end]:
             little_end = i
         else:
             large_start = i if large_start == end else large_start
     head.left = rebuild(value, start, little_end)
     head.right = rebuild(value, large_start, end - 1)
     return head
 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 rebuild_tree(value_list):
     """
     利用列表保存的二叉树节点值重建二叉树
     :param value_list:
     :return:
     """
     if not len(value_list):
         return
     node_value = value_list.pop(0)
     if node_value == "#":
         return None
     node = Node(node_value)
     node.left = rebuild_tree(value_list)
     node.right = rebuild_tree(value_list)
     return node
Exemple #25
0
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]
Exemple #26
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 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 generate(value, start, end):
     """
     利用value[start,end]生产平衡搜索二叉树
     :type value:list
     :type start:int
     :type end:int
     :param value:
     :param start:
     :param end:
     :return:
     """
     if start > end:
         return None
     mid = (start + end) // 2
     head = Node(value[mid])
     head.left = generate(value, start, mid - 1)
     head.right = generate(value, mid + 1, end)
     return head
Exemple #31
0
def btree1():
    el1 = Node(1)
    el2 = Node(2)
    el3 = Node(3)
    el4 = Node(4)
    el5 = Node(5)
    el6 = Node(6)

    el1.left = el2
    el1.right = el3
    el1.left.left = el4
    el1.left.right = el5
    el1.left.left.left = el6

    return BinaryTree(el1)
    def _createTree(self, inorder, preorder, start, end):
        if start > end:
            return None
        i = 0
        for i in range(start, end + 1):
            if preorder[self.index] == inorder[i]:
                break

        node = Node.newNode(preorder[self.index])
        self.index += 1
        node.left = self._createTree(inorder, preorder, start, i - 1)
        node.right = self._createTree(inorder, preorder, i + 1, end)
        return node
from binary_tree import Node

def path_sum(root, num, path=[]):
    if sum(path) + root.value == num:
        print path + [root.value]
    if root.left:
        path_sum(root.left, num, path+[root.value])
    if root.right:
        path_sum(root.right, num, path+[root.value])

if __name__ == '__main__':
    root = Node(1)
    root.left, root.right = Node(2), Node(1)
    root.left.left, root.left.right = Node(1), Node(0)
    root.right.left, root.right.right = Node(1), Node(3)
    print """
    root =
          1
        2   1
       1 0 1 3
    """
    print 'now running path_sum(root, 3)'
    path_sum(root, 3)
Exemple #34
0
	def __init__(self, data, n):
		HashTree.__init__(self, data, 1, n+1) 
        elif left:
            return is_bst(left, min, value)
        elif right:
            return is_bst(right, value, max)
        return True
    return False

"""
BST
      4
   2     6
 1   3 5   7

BT
      4
   2     6
 1   8 5   7
"""

if __name__ == '__main__':
    bst = Node(4)
    bst.left, bst.right = Node(2), Node(6)
    bst.left.left, bst.left.right = Node(1), Node(3)
    bst.right.left, bst.right.right = Node(5), Node(7)
    bt = Node(4)
    bt.left, bt.right = Node(2), Node(6)
    bt.left.left, bt.left.right = Node(1), Node(8)
    bt.right.left, bt.right.right = Node(5), Node(7)
    print 'is_bst(bst) =', is_bst(bst)
    print 'is_bst(bt) =', is_bst(bt)
Exemple #36
0
                                                                              node.left.data,
                                                                              node.right.data, )
            return False
    else:
        return True


if __name__ == '__main__':
    """ Successfull Case """
    binary_tree = BinaryTree()
    for value in [5, 2, 1, 9, 10, 0, 6]:
        binary_tree.insert(value)
    if is_bst(binary_tree.root):
        print "its a BST"
    else:
        print "it not a BST"

    """ Root is null case """
    is_bst(None)

    """ Unsuccessful case """
    # Lets construct an invalid tree
    parent_node = Node(5)
    parent_node.left = Node(6)
    parent_node.right = Node(8)
    if is_bst(parent_node):
        print "its a BST"
    else:
        print "it not a BST"