Example #1
0
def radix_tree_insert(tree, string, label):
    """inserts a binary string in a radix tree
    args:
        tree: Node, radix_tree
        string: str, to be inserted ( 01011, 1001, .. )
        label: label the end of the string with
    """
    curr = tree
    for i, char in enumerate(string):

        # traverse the binary tree adding nodes if required
        if char == '1':
            if not curr.right:
                curr.right = Node(1)
            curr = curr.right
        elif char == '0':
            if not curr.left:
                curr.left = Node(0)
            curr = curr.left

        # marks the termination of strings
        if i == len(string) - 1:
            curr.end = label
        elif (hasattr(curr, 'end') and curr.end < 0) \
                or not hasattr(curr, 'end'):
            curr.end = -1
Example #2
0
 def setUp(self):
     tree = Node(5)
     tree.left = Node(3)
     tree.left.right = Node(5)
     tree.left.left = Node(2)
     tree.right = Node(7)
     tree.right.right = Node(8)
     self.tree = tree
Example #3
0
 def insert(self,
            new_node: Any,
            current: Node,
            parent: Node = None) -> None:
     if self.root is None:
         self.root = new_node
         return
     parent = current
     if current.key < new_node.key:
         current = current.right
     else:
         current = current.left
     if current:
         # recursive
         self.insert(new_node, current, parent)
     else:
         if parent.key < new_node.key:
             parent.right = new_node
         else:
             parent.left = new_node
Example #4
0
def pQueue(dictionary):

    # Instantiate a PriorityStack object
    pqueue = PriorityStack()

    # Create the nodes for the tree
    for char, freq in dictionary.items():
        node = Node(freq, char, None)  # sorting by keys, so freq is now key
        pqueue.push(node.key, node)

    # Create the tree
    while True:
        # Pop the first two values so that they can become children of a single parent node... or not.
        freq1, value1 = pqueue.pop()
        freq2, value2 = pqueue.pop()

        # Return what tree?
        if value1 is None:
            return None

        # return the whole tree
        elif value2 is None:
            return value1

        else:
            """
            1. create the key of the parent node of the first two values in the priority queue
            2. Create the node, which is empty because it isn't a leaf
            3. Set the left and right children of the parent node
            4. Push value3 to the priority queue because it isn't a root, and needs to attached to another node
                a. Pass the key of the parent node for the sake of the priority stack
                b. Pass the node as the value
            """
            freq3 = freq1 + freq2
            value3 = Node(freq3, None, None)
            value3.left_child = value1
            value3.right_child = value2
            pqueue.push(value3.key, value3)
Example #5
0
def main():
    args = parse_argument()
    log.debug(args)

    if args.max_num == 3:
        from test_binary_search_tree import three_data as data
    elif args.max_num == 5:
        from test_binary_search_tree import five_data as data
    elif args.max_num == 8:
        from test_binary_search_tree import eight_data as data
    elif args.max_num == 12:
        from test_binary_search_tree import twelve_data as data
    elif args.max_num == 17:
        from test_binary_search_tree import seventeen_data as data
    else:
        data = list(random.sample(range(args.max_num), args.max_num))

    log.info(data)
    first = data.pop(0)
    root = Node(first, 'root')

    bst = BinarySearchTree(root)
    for i in data:
        bst.insert(i)

    print('=== initial tree structure ===')
    bst.show()

    if args.target_key is not None:
        set_parent(bst.root)
        key = args.target_key
        node = bst.search(key)
        print('search:', node)

        if node.attr == 'left' or node.attr == 'root':
            print('=== target %d, rotating left ===' % key)
            rotate_left(node, bst)
            bst.show()

            print('=== target %d, rotating right ===' % node.parent.key)
            rotate_right(node.parent, bst)
            bst.show()
        elif node.attr == 'right':
            print('=== target %d, rotating right ===' % key)
            rotate_right(node, bst)
            bst.show()

            print('=== target %d, rotating left ===' % node.parent.key)
            rotate_left(node.parent, bst)
            bst.show()
Example #6
0
def tree_insert(tree, val):
    """CLRS pg. 261, insert a new node in the BST
    args:
        tree: Node BST
        val: value to be inserted
    returns:
        Node: the new tree
    """
    prev, res = None, tree
    while tree:
        prev = tree
        if tree.val > val:
            tree = tree.left
        elif tree.val < val:
            tree = tree.right
        else:
            return res
    if prev is None:
        return Node(val)
    elif prev.val > val:
        prev.left = Node(val)
    else:
        prev.right = Node(val)
    return res
def animation():
    size = 10
    numbers = gen_numbers(size)
    root = None
    ga = Animation()
    # generate tree
    for n in numbers:
        root = insert(root, Node(n))
        add_nodes(ga, root)
        ga.highlight_node(n)
        ga.next_step(clean=True)
    # delete
    for n in gen_numbers(size):
        add_nodes(ga, root)
        ga.highlight_node(n)
        ga.next_step(clean=True)
        root = delete(root, search(root, n))

    # save
    graphs = ga.graphs()
    files = render(graphs, "figure/figure", 'png')
    gif(files, "figure/gif-anim", 50)
Example #8
0
def sort_strings(strings):
    """sorts set of binary strings lexicographically
    args:
        strings: list(strings), binary strings in the form 00101..
    returns:
        list(strings) sorted
    """
    # populating the radix tree
    tree = Node('#')
    for i, string in enumerate(strings):
        radix_tree_insert(tree, string, i)

    # BFS on the radix tree
    res, queue = [], [tree]
    while queue:
        node = queue.pop()
        if hasattr(node, 'end') and not node.end < 0:
            res.append(strings[node.end])
        if node.right:
            queue.insert(0, node.right)
        if node.left:
            queue.insert(0, node.left)
    return res
Example #9
0
 def setUp(self):
     self.tree = Node('#')
            left = None
        if left and right:
            if right < left:
#                print("Left greater than right")
                raise Exception
    else:
        return True
    is_valid(root.right)
    is_valid(root.left)
    
if __name__ == "__main__":
    tree = Tree()
    tree.insert(1)
    tree.insert(2)
    tree.insert(10)
    tree.insert(6)
    try:
        is_valid(tree.root)
    except:
        print("Tree is invalid")
     
        
    invalid_root = Node(2)
    right = Node(4)
    left = Node(5)
    invalid_root.right = right
    invalid_root.left = left
    try:
        is_valid(invalid_root)
    except:
        print("The invalid tree was classified as is invalid")
Example #11
0


def create_level_linked_list(root, lists, level):
  if (root == None):
    return 
  if (len(lists) == level): ## if the level has not been reached
    list = LL_Node(root.item)
    lists.append(list)
  else:
    list = lists[level]
    new = LL_Node(root.item)
    new.next = list
    list = new
    lists[level] = list
  create_level_linked_list(root.left, lists, level + 1)
  create_level_linked_list(root.right, lists, level + 1)

def create_linked_list(root):
  lists = []
  create_level_linked_list(root, lists, 0)
  return lists


tree = Node(1, None, None)
tree.left = Node(2, None, None)
tree.right = Node(3, None, None)

r = create_linked_list(tree)
print(r[1].next)
def insert_tree(data):
    root = Node(data[0], 'root')
    bst = BinarySearchTree(root)
    for i in data[1:]:
        bst.insert(i)
    return bst
from binary_search_tree import Node


def level_order_traversal(queue, result):
    if queue:
        node = queue.pop(0)
        if node is not None:
            if node.left is not None:
                queue.append(node.left)
            if node.right is not None:
                queue.append(node.right)
            result.append(node)
        result = level_order_traversal(queue, result)
    return result


if __name__ == '__main__':
    root = Node('A')
    queue = [root]
    root.left = Node('B')
    root.left.left = Node('D')
    root.left.right = Node('E')
    root.left.left.left = Node('G')
    root.left.right.right = Node('H')
    root.right = Node('C')
    root.right.right = Node('F')
    root.right.right.left = Node('I')

    print('Level-Order Traversal', level_order_traversal([root], []))
Example #14
0
    def setUpClass(cls):
        cls.bst1_node1 = Node(6)
        cls.bst1_node2 = Node(5, cls.bst1_node1)
        cls.bst1_node3 = Node(7, cls.bst1_node1)
        cls.bst1_node4 = Node(2, cls.bst1_node2)
        cls.bst1_node5 = Node(5, cls.bst1_node2)
        cls.bst1_node6 = Node(8, cls.bst1_node3)
        cls.bst1_node1.left = cls.bst1_node2
        cls.bst1_node1.right = cls.bst1_node3
        cls.bst1_node2.left = cls.bst1_node4
        cls.bst1_node2.right = cls.bst1_node5
        cls.bst1_node3.right = cls.bst1_node6
        cls.bst1 = BinarySearchTree(cls.bst1_node1)
        cls.bst1_inorder_str = "2\n5\n5\n6\n7\n8\n"

        cls.bst2_node1 = Node(2)
        cls.bst2_node2 = Node(5, cls.bst2_node1)
        cls.bst2_node3 = Node(7, cls.bst2_node2)
        cls.bst2_node4 = Node(6, cls.bst2_node3)
        cls.bst2_node5 = Node(8, cls.bst2_node3)
        cls.bst2_node6 = Node(5, cls.bst2_node4)
        cls.bst2_node1.right = cls.bst2_node2
        cls.bst2_node2.right = cls.bst2_node3
        cls.bst2_node3.left = cls.bst2_node4
        cls.bst2_node3.right = cls.bst2_node5
        cls.bst2_node4.left = cls.bst2_node6
        cls.bst2 = BinarySearchTree(cls.bst2_node1)
        cls.bst2_inorder_str = "2\n5\n5\n6\n7\n8\n"
Example #15
0
def create_node(id_, value):
    return Node(id_, value)
def huffman_code(characters, weights):
    # this dictionary is used for finding characters also insert new pair of merged characters
    address = {}
    # to save and hold Nodes and also values
    nodes = []
    values = []
    # for loop to fill address dictionary
    for index in range(len(characters)):
        address[weights[index]] = characters[index]
    # create a heap for minimum calculation
    heap = Heap(weights)
    # repeat step in the while loop until heap length become one
    while heap.length > 1:
        # find two most minimum values
        min_number_one, min_number_two = heap.min(), heap.min()
        # find corresponding characters in address dictionary
        char_number_one, char_number_two = address.get(
            min_number_one), address.get(min_number_two)
        summed_values = min_number_one + min_number_two
        # merging characters and insert it to address and also heap
        address[summed_values] = ''.join([char_number_one, char_number_two])
        heap.insert(summed_values)
        # create a Node and insert it to tree
        if min_number_one in values:
            for node in nodes:
                if node.value is min_number_one:
                    min_number_one = node
        else:
            values.append(min_number_one)
            min_number_one = Node(value=min_number_one)

        if min_number_two in values:
            for node in nodes:
                if node.value is min_number_two:
                    min_number_two = node
        else:
            values.append(min_number_two)
            min_number_two = Node(value=min_number_two)

        new_node = Node(value=summed_values,
                        left_child=min_number_one,
                        right_child=min_number_two)
        min_number_one.parent, min_number_two.parent = new_node, new_node
        nodes.append(min_number_one)
        nodes.append(min_number_two)
        nodes.append(new_node)
        values.append(summed_values)

    # cleaning address from waste items and only keep first generation weights
    number_of_items_must_be_removed = len(address.items()) - len(weights)
    for item in range(number_of_items_must_be_removed):
        address.popitem()

    # this function is return address of a weight
    def node_address(key):
        list_of_binaries = []
        loop_backed_node = None

        for node in nodes:
            if node.value is key:
                loop_backed_node = node

        while loop_backed_node.parent is not None:
            parent_node = loop_backed_node.parent
            if parent_node.left_child.value is loop_backed_node.value:
                list_of_binaries.append(0)
            else:
                list_of_binaries.append(1)

            loop_backed_node = loop_backed_node.parent

        return list(reversed(list_of_binaries))

    list_of_letter_binary_value = []
    for weight in weights:
        value = node_address(key=weight)
        letter = address.get(weight)
        list_of_letter_binary_value.append([letter, value])

    return list_of_letter_binary_value
Example #17
0
from binary_search_tree import Node

node = Node(1)
print(node.get())
node.set(2)
print(node.get())