示例#1
0
 def __percolate_down(self, node: BinaryNode) -> None:
     """
     Bubble up heap operation
     """
     min_child = node.get_min_child()
     if min_child and min_child.value < node.value:
         node.value, min_child.value = min_child.value, node.value
         self.__percolate_down(min_child)
示例#2
0
    def test_question_1(self):

        tree_1 = BinaryNode.from_array([1, 2 ,3, 4, 5, 6, 7])

        assert tree_1.is_balanced()

        leaf_node = next(tree_1.get_leaf_nodes())

        leaf_node.rnode = BinaryNode(0)
        leaf_node.rnode.rnode = BinaryNode(0)

        assert not tree_1.is_balanced()
示例#3
0
 def __percolate_up(self, node: BinaryNode) -> None:
     """
     Trickle down heap operation
     """
     if node.parent and node.parent.value > node.value:
         node.value, node.parent.value = node.parent.value, node.value
         self.__percolate_up(node.parent)
示例#4
0
    def __init__(self, data=None):
        if data is None:
            data = []

        self.heap_size = len(data)
        self._root = BinaryNode.from_array(data) # type: BinaryNode

        self.heapify()
示例#5
0
    def insert(self, value):
        """
        Insert a node at the bottom of the tree and percolate it up
        """
        parent = self.__find_new_parent()

        node = BinaryNode(value)

        if parent is None:
            self._root = node
        else:
            if parent.lnode:
                parent.rnode = node
            else:
                parent.lnode = node

        self.__percolate_up(node)

        self.heap_size += 1
示例#6
0
def is_balanced(root: BinaryNode):
    return root.is_balanced()