예제 #1
0
        def reconstruct(in_lst, pre_lst, prev_val):
            if not pre_lst:
                return

            lft_inodr, right_inodr = [], []
            lft_preord, right_preord = [], []
            n = pre_lst[0]
            node = Node(n)
            for in_n, pre_n in zip(in_lst, pre_lst):
                if in_n < n:
                    lft_inodr.append(in_n)
                if in_n > n:
                    right_inodr.append(in_n)
                if pre_n < n:
                    lft_preord.append(pre_n)
                if pre_n > n:
                    right_preord.append(pre_n)

            node.left = reconstruct(lft_inodr, lft_preord, n)
            node.right = reconstruct(right_inodr, right_preord, n)

            return node
예제 #2
0
 def insert(self, value):
     pointer = None
     node = self.root
     new_node = Node(value)
     while node:
         pointer = node
         if value < node.value:
             node = node.left
         else:
             node = node.right
     if not pointer:
         # the tree is empty
         self.root = new_node
     elif value < pointer.value:
         pointer.left = new_node
     else:
         pointer.right = new_node
 def create_test_root(self):
     root = Node(1)
     root.left, root.right = Node(2), Node(3)
     root.left.left, root.left.right = Node(4), Node(5)
     root.right.left, root.right.right = Node(6), Node(7)
     return root
 def create_unbalanced_root(self):
     root = Node(6)
     root.left, root.right = Node(4), Node(7)
     root.left.left, root.left.right = Node(2), Node(5)
     root.left.left.left, root.left.left.right = Node(1), Node(3)
     return root
 def test_find_lowest_common_ancestor(self):
     node_a, node_b = Node(2), Node(5)
     expected_lca = Node(4)
     result_lca = self.tree.find_lowest_common_ancestor(node_a, node_b)
     assert_that(result_lca).is_equal_to(expected_lca)