def test_height(self):
     # Create node with no children
     node = BinaryTreeNode(2)
     assert node.height() == 0
     # Attach left child node
     node.left = BinaryTreeNode(1)
     assert node.height() == 1
     # Attach right child node
     node.right = BinaryTreeNode(3)
     assert node.height() == 1
     # Attach right child node to right node child
     node.right.right = BinaryTreeNode(5)
     assert node.height() == 2
     # Attach right child node to previously attached right node child
     node.right.right.right = BinaryTreeNode(7)
     assert node.height() == 3
     # Detach right leaf node
     node.right.right.right = None
     assert node.height() == 2
     # Detach right leaf node again
     node.right.right = None
     assert node.height() == 1
     # Detach left child node
     node.left = None
     assert node.height() == 1
     # Detach right child node
     node.right = None
     assert node.height() == 0
    def test_height(self):
        # Create node with no children
        node = BinaryTreeNode(2)
        assert node.height() == 0

        # Add child
        node.left = BinaryTreeNode(1)
        assert node.height() == 1

        # Add grandchild on left side
        node.left.right = BinaryTreeNode(4)
        assert node.height() == 2
Ejemplo n.º 3
0
def test_1():
    root = BinaryTreeNode(
        1,
        BinaryTreeNode(2, BinaryTreeNode(4, BinaryTreeNode(8)),
                       BinaryTreeNode(5)),
        BinaryTreeNode(3, BinaryTreeNode(6),
                       BinaryTreeNode(7, None, BinaryTreeNode(9))))
    assert ([[node.data for node in level]
             for level in nodes_in_levels(root)] == [[1], [2, 3], [4, 5, 6, 7],
                                                     [8, 9]])
Ejemplo n.º 4
0
    def constructtree(self, preorder, inorder, k1, Lk1, k2, Lk2):
        rootval = preorder[k1]
        root = BinaryTreeNode(rootval)

        if k1 == Lk1:
            if k2 == Lk2 and preorder[k1] == inorder[k2]:
                return root
            else:
                raise ValueError

        rootino = k2
        while rootino <= Lk2 and inorder[rootino] != rootval:
            rootino += 1

        if rootino == Lk2 and inorder[rootino] != rootval:
            raise ValueError

        leftlength = rootino - k2
        leftpreo = k1 + leftlength

        if leftlength > 0:
            root.left_ = self.constructtree(preorder, inorder, k1 + 1,
                                            leftpreo, k2, rootino - 1)

        if leftlength < (Lk1 - k1):
            root.right_ = self.constructtree(preorder, inorder, leftpreo + 1,
                                             Lk1, rootino + 1, Lk2)
        return root
 def test_is_branch(self):
     # Create node with no children
     node = BinaryTreeNode(2)
     assert node.is_branch() is False
     # Attach left child node
     node.left = BinaryTreeNode(1)
     assert node.is_branch() is True
     # Attach right child node
     node.right = BinaryTreeNode(3)
     assert node.is_branch() is True
     # Detach left child node
     node.left = None
     assert node.is_branch() is True
     # Detach right child node
     node.right = None
     assert node.is_branch() is False
Ejemplo n.º 6
0
    def create_base_pq(self):
        q = MinPQ()
        for letter, n in self.letter_counts.items():
            n = BinaryTreeNode((n, letter))
            q.insert(n)

        return q
Ejemplo n.º 7
0
    def create_huffmancode(self):
        while len(self.pq) > 1:
            x = self.pq.extract()
            y = self.pq.extract()
            combined_score = x.d[0] + y.d[0]
            z = BinaryTreeNode((combined_score, None), x, y)
            self.pq.insert(z)

        return self.pq.extract()
Ejemplo n.º 8
0
 def deserializetree(self, ls):
     if len(ls) <= 0:
         return None
     val = ls.pop(0)
     root = None
     if val != '$':
         root = BinaryTreeNode(int(val))
         root.left_ = self.deserializetree(ls)
         root.right_ = self.deserializetree(ls)
     return root
Ejemplo n.º 9
0
def test_1():
    from operator import attrgetter
    tree = BinaryTreeNode(
        3, BinaryTreeNode(1, BinaryTreeNode(0), BinaryTreeNode(2)),
        BinaryTreeNode(6, BinaryTreeNode(4, None, BinaryTreeNode(5)),
                       BinaryTreeNode(7)))
    nodes = list(tree.inorder())
    assert nodes == sorted(nodes, key=attrgetter('data'))

    expected_next_nodes = nodes[1:] + [None]

    for node, next_node in zip(nodes, expected_next_nodes):
        assert get_next_node(node) is next_node
Ejemplo n.º 10
0
 def insert(self, key, val):
     """Insert the given item in order into this binary search tree.
     Best case: O(1) if the tree is empty
     Worst case: O(n) if the tree is very unbalanced
     Worst cast with balanced tree: o(log(n))"""
     if self.is_empty():  # Handle the case where the tree is empty
         self.root = BinaryTreeNode((key, val))  # Create a new root node
         self.size += 1  # Increase the tree size
         return
     # Find the parent node of where the given item should be inserted
     parent = self._find_parent_node_recursive(item, self.root)
     if key < parent.data and parent.left == None:  # Check if the given item should be inserted left of parent node
         parent.left = BinaryTreeNode(
             (key,
              val))  # Create a new node and set the parent's left child
         self.size += 1  # Increase the tree size
     elif key > parent.data and parent.right == None:  # Check if the given item should be inserted right of parent node
         parent.right = BinaryTreeNode(
             (key,
              val))  # Create a new node and set the parent's right child
         self.size += 1  # Increase the tree size
Ejemplo n.º 11
0
 def test_height(self):
     second_child_node = BinaryTreeNode(7)
     second_child_node.right = BinaryTreeNode(8)
     child_node = BinaryTreeNode(1)
     child_node.left = second_child_node
     child_node.right = BinaryTreeNode(6)
     node = BinaryTreeNode(2)
     node.right = BinaryTreeNode(3)
     assert node.height() == 1
     node.left = child_node
     assert node.height() == 3
Ejemplo n.º 12
0
    def test_height(self):
        left_node = BinaryTreeNode(3)
        root_node = BinaryTreeNode(5)
        right_node = BinaryTreeNode(8)

        root_node.left = left_node
        root_node.right = right_node

        left_node_of_left = BinaryTreeNode(2)
        right_node_of_Left = BinaryTreeNode(4)

        left_node.left = left_node_of_left
        left_node.right = right_node_of_Left

        left_node_of_left_node_of_left = BinaryTreeNode(1)
        left_node_of_left.left = left_node_of_left_node_of_left

        right_node_right = BinaryTreeNode(9)
        right_node.right = right_node_right

        assert root_node.height() == 3
 def test_height(self):
     # Create node with no children
     node = BinaryTreeNode(4)
     assert node.height() == 0
     # Attach left child node
     node.left = BinaryTreeNode(2)
     assert node.height() == 1
     # Attach right child node
     node.right = BinaryTreeNode(6)
     assert node.height() == 1
     # Attach left-left grandchild node
     node.left.left = BinaryTreeNode(1)
     assert node.height() == 2
     # Attach right-right grandchild node
     node.right.right = BinaryTreeNode(8)
     assert node.height() == 2
     # Attach right-right-left great-grandchild node
     node.right.right.left = BinaryTreeNode(7)
     assert node.height() == 3
 def test_init(self):
     data = 123
     node = BinaryTreeNode(data)
     assert node.data is data
     assert node.left is None
     assert node.right is None
Ejemplo n.º 15
0
def second_largest(root: BinaryTreeNode) -> BinaryTreeNode:
    node = root
    parent = root
    while node.right is not None:
        parent = node
        node = node.right
    if node.left is None:
        return parent
    else:
        node = node.left
        while node.right is not None:
            node = node.right
        return node

no_left_bst = BinaryTreeNode(5)
no_left_bst.insert_left(4)
no_left_bst.insert_right(6)
no_left_bst.right.insert_right(7)

print(second_largest(no_left_bst).value)

left_bst = BinaryTreeNode(5)
left_bst.left = BinaryTreeNode(3)
left_bst.right = BinaryTreeNode(8)
left_bst.right.left = BinaryTreeNode(7)
left_bst.right.right = BinaryTreeNode(12) #largest
left_bst.right.right.left = BinaryTreeNode(10) #left tree of largest
left_bst.right.right.left.left = BinaryTreeNode(9)
left_bst.right.right.left.right = BinaryTreeNode(11) #second largest
Ejemplo n.º 16
0
    if high_limit is not None and root.value >= high_limit:
        return False

    if low_limit is not None and root.value < low_limit:
        return False

    if root.left and not validate(root.left, low_limit, root.value):
        return False

    if root.right and not validate(root.right, root.value, high_limit):
        return False

    return True


n = BinaryTreeNode(10)
n.insert(15)
n.insert(1)
n.insert(8)
n.insert(20)
n.insert(12)
n.insert(7)

assert validate(n)
twenty = n.find(20)
# 5 is less than root of 10, but is on the right side of tree
twenty.insert(5)
# tree now invalid
assert not validate(n)
print('All tests passed!')
Ejemplo n.º 17
0
    while len(stack) != 0:
        node, depth = stack.pop()
        if isLeaf(node):
            if deepest is None and shallowest is None:
                deepest, shallowest = depth, depth
            if depth > deepest:  
                deepest = depth
            if depth < shallowest:
                shallowest = depth
            if (deepest - shallowest) > 1:
                return False
        if node.left is not None:
            stack.append((node.left, depth+1))
        if node.right is not None:
            stack.append((node.right, depth+1))
    return True

def isLeaf(node: BinaryTreeNode):
    return node.left is None and node.right is None

sb = BinaryTreeNode(1)
sb.left = BinaryTreeNode(2)
sb.right = BinaryTreeNode(3)

nb = BinaryTreeNode(1)
nb.left =BinaryTreeNode(2)
nb.right = BinaryTreeNode(3)
nb.left.left = BinaryTreeNode(4)
nb.left.left.left = BinaryTreeNode(5) 

print(isSuperBalanced(sb))
Ejemplo n.º 18
0
def test_1():
    # True case
    tree1 = BinaryTreeNode(
        5, BinaryTreeNode(3, BinaryTreeNode(2), BinaryTreeNode(4)),
        BinaryTreeNode(7, BinaryTreeNode(6), BinaryTreeNode(8)))
    assert is_binary_search_tree(tree1) == True

    # False case2
    tree2 = BinaryTreeNode(
        5, BinaryTreeNode(3, BinaryTreeNode(2), BinaryTreeNode(3)),
        BinaryTreeNode(7, BinaryTreeNode(6), BinaryTreeNode(8)))
    assert is_binary_search_tree(tree2) == False

    # False case3
    tree3 = BinaryTreeNode(
        5, BinaryTreeNode(3, BinaryTreeNode(2), BinaryTreeNode(3)),
        BinaryTreeNode(7, BinaryTreeNode(5), BinaryTreeNode(8)))
    assert is_binary_search_tree(tree3) == False
 def test_one_case(self):
     tree = BinarySearchTree()
     node = BinaryTreeNode(3)
     tree.insert(3)
     assert tree.size == 1
     assert tree._find_parent_node_recursive(3, tree.root) == None
Ejemplo n.º 20
0
from binarytree import BinaryTreeNode

def is_bst(root: BinaryTreeNode) -> bool:
    upper_bound = float('inf')
    lower_bound = -float('inf')
    return is_bst_helper(root, upper_bound, lower_bound)


def is_bst_helper(root: BinaryTreeNode, upper_bound: float, lower_bound: float) -> bool:
    if root is None:
        return True
    if root.value > lower_bound and root.value < upper_bound:
        return is_bst_helper(root.left, root.value, lower_bound) and is_bst_helper(root.right, upper_bound, root.value)
    return False


bst = BinaryTreeNode(5)
bst.insert_left(4)
bst.insert_right(6)
bst.right.insert_right(7)

print(is_bst(bst))

badBst = BinaryTreeNode(7)
badBst.insert_left(6)
badBst.insert_right(15)
badBst.left.insert_right(8) # bad value -- bigger than root

print(is_bst(badBst))