Example #1
0
def test_bst_generation():
    for invalid_height in ['foo', -1, None]:
        with pytest.raises(TreeHeightError) as err:
            bst(height=invalid_height)
        assert str(err.value) == 'height must be an int between 0 - 9'

    root = bst(height=0)
    root.validate()
    assert root.height == 0
    assert root.left is None
    assert root.right is None
    assert isinstance(root.value, int)

    for _ in range(REPETITIONS):
        random_height = random.randint(1, 9)
        root = bst(random_height)
        root.validate()
        assert root.is_bst is True
        assert root.height == random_height

    for _ in range(REPETITIONS):
        random_height = random.randint(1, 9)
        root = bst(random_height, is_perfect=True)
        root.validate()
        assert root.height == random_height

        if not root.is_bst:
            print(root)
            raise Exception('boo')

        assert root.is_bst is True
        assert root.is_perfect is True
        assert root.is_balanced is True
        assert root.is_strict is True
Example #2
0
def main():
    tree1 = bst(height=2, is_perfect=False)
    tree2 = bst(height=2, is_perfect=False)
    print('-----------------------------------------------------')
    print('tree1 {}:'.format(len(tree1)))
    print(tree1)
    print('tree2 {}:'.format(len(tree2)))
    print(tree2)
    res = print_trees(tree1, tree2)
    print('{} {}'.format(len(res), res))
    if len(res) != len(tree1) + len(tree2):
        raise Exception('Incorrect!')
    for i, v in enumerate(res):
        if i > 0:
            if res[i - 1] > res[i]:
                raise Exception('Incorrect!')
Example #3
0
    def test_creation(self):
        # this creates a fully-populated binary-search-tree of depth 4, on the numbers [0, 30]
        root = binarytree.bst(height=4, is_perfect=True)

        # DEBUG
        # print(root)

        # ==== generates this tree: ====
        #                 ___________________15_____________________
        #                /                                          \
        #         ______7_______                           __________23_________
        #        /              \                         /                     \
        #     __3__           ___11___               ____19___               ____27___
        #    /     \         /        \             /         \             /         \
        #   1       5       9         _13         _17         _21         _25         _29
        #  / \     / \     / \       /   \       /   \       /   \       /   \       /   \
        # 0   2   4   6   8   10    12    14    16    18    20    22    24    26    28    30
        #
        self.assertEqual(root.height, 4)

        # spot check -- *not full* check:
        self.assertEqual(root.value, 15)
        self.assertEqual(root.right.value, 23)
        self.assertEqual(root.right.left.value, 19)
        self.assertEqual(root.right.left.left.value, 17)
        self.assertEqual(root.right.left.left.left.value, 16)
        self.assertEqual(root.right.left.left.right.value, 18)
Example #4
0
    def test_from_array_representation(self):
        bst = BinarySearchTree.from_array_representation([])
        self.assertEqual(bst, self.empty_bst)

        array = binarytree.bst(height=random.randint(0, 9),
                               is_perfect=random.choice([True, False])).values
        bst = BinarySearchTree.from_array_representation(array)
        self.assertEqual(array, bst.to_array_representation())
Example #5
0
def main():
    bst_root = bst(height=2)
    k = 6
    print('k: ', k)
    print('bst: ', bst_root)

    result = has_element(bst_root, k)
    print(result)
Example #6
0
def main():
    bst_root = bst(height=3)
    k = 6
    path = []
    print('k: ', k)
    print('bst: ', bst_root)

    result = find_with_path(bst_root, k, path)
    print(result)
 def repeat_checks(tree_cls: Type[BinarySearchTree], height: int,
                   n_checks: int):
     """Repeatedly check the correctness of the operations of a binary search
     tree.
     """
     for _ in range(n_checks):
         ref = bst(height=height)
         target = tree_cls.from_list_repr(ref.values)
         assert target.list_repr == ref.values
         CHECK_TREE_AND_SUB_TREE(target, ref)
         TestBinarySearchTree.check_op_search(
             target, TestBinarySearchTree._N_SEARCH_OP_CHECK)
         TestBinarySearchTree.check_op_insert_delete(target)
         TestBinarySearchTree.check_op_inorder_successor(target)
Example #8
0
def main():
    from binarytree import tree, bst, heap, Node  # https://pypi.org/project/binarytree/
    root = bst(height=3)
    # root = Node(1)
    # root.left = Node(2)
    # root.right = Node(3)
    # root.left.left = Node(4)
    # root.left.right = Node(5)
    # root.right.right = Node(10)
    # root.right.right.left = Node(11)

    # add 1 to module answer because module counts edges (N) and solution counts nodes (N+1)
    print(root)
    print(findMinDepthOfBSTByNodes(root), root.min_leaf_depth + 1)
    print(checkAnswer(findMinDepthOfBSTByNodes(root), root.max_leaf_depth + 1))
    def setUp(self):
        self.empty_bst = BinarySearchTree()

        self.one_node_bst = BinarySearchTree()
        self.one_node_bst.insert(1)

        #     ______8
        #    /       \
        #   3__       10___
        #  /   \           \
        # 1     6          _14
        #      / \        /
        #     4   7      13
        self.insert_items = [8, 3, 10, 1, 6, 14, 4, 7, 13]
        self.bst = BinarySearchTree()
        for i in self.insert_items:
            self.bst.insert(i)

        array = binarytree.bst(is_perfect=True).values
        self.perfect_bst = BinarySearchTree.from_array_representation(array)
Example #10
0
                    cur = cur.right
            if not cur:
                flag = 0
                cur = self.root

        if not cur:
            print("could not generate the random number")
            return 0

    def get_randomnode_1(self):
        index = random.randint(0, self.root.size)
        while True:
            val = get_i_node(self.root, index)
            if val != None:
                return val


if __name__ == "__main__":
    n = int(input("what is height of tree?"))
    head = bst(n)
    lt = convert(head)
    bshead = bs_tree()
    for i in range(len(lt)):
        if lt[i]:
            bshead.insert(knode(lt[i]))
    print("Input Binary tree is ")
    pprint(bshead.root)
    while True:
        input("enter key to genearte a random number")
        print("The random value = %d" % bshead.get_randomnode())
Example #11
0

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if nums == []:
            return None
        mid = len(nums) // 2
        root = TreeNode(nums[mid])
        root.left = self.sortedArrayToBST(nums[:mid])
        root.right = self.sortedArrayToBST(nums[mid + 1:])
        return root


data = [-10, -3, 0, 5, 9]
from binarytree import build
from binarytree import tree, bst, heap
root = build(data)
my_bst = bst(height=3, is_perfect=True)
print(root)
# бинарный поиск

from binarytree import bst

def search(bin_search_tree, number, path=''):
	if bin_search_tree.value == number:
		return f'Число {number} обнаружено по следующему пути:\nКорень {path}'
	
	if number < bin_search_tree.value and bin_search_tree.left != None:
		return search(bin_search_tree.left, number, path=f'{path}\nШаг влево')

	if number > bin_search_tree.value and bin_search_tree.right != None:
		return search(bin_search_tree.right, number, path=f'{path}\nШаг вправо')

	return f'Число {number} отсутствует в дереве'
	

bt = bst(height=5, is_perfect=False)
print(bt)

num = int(input('Введите число для поиска: '))
print(search(bt, num))

Example #13
0
    if t.left != None:
        target = FindKthNodeCore(t.left, k)

    print(t.value)
    if target == None:
        if k == 1:  #命中目标
            target = t
        k -= 1

    if target == None and t.right != None:
        target = FindKthNodeCore(t.right, k)
    return target


bst_tree = bst(3)
print(bst_tree)
n = 5
re = FindKthNode(bst_tree, n)
print('二叉搜索树第{}大数: {}'.format(n, re))


# 合并二叉树
# https://leetcode-cn.com/problems/merge-two-binary-trees/comments/
# 输入:
# 	Tree 1                     Tree 2
#           1                         2
#          / \                       / \
#         3   2                     1   3
#        /                           \   \
#       5                             4   7
Example #14
0
    print(" %s" % max_val)

    if root.value < min_val or root.value > max_val:
        return False

    return is_bst_valid_rec(root.left, min_val,
                            root.value) and is_bst_valid_rec(
                                root.right, root.value, max_val)


def is_bst_valid(root):
    #return is_bst_valid_rec(root, float('-inf'), float('inf'))
    return is_bst_valid_inorder(root)


bst_tree = bst(height=3)
print(bst_tree)
test('valid_bst', is_bst_valid(bst_tree), True)

non_bst = tree(height=3)
print(non_bst)
test('invalid bst - simple', is_bst_valid(non_bst), False)

non_bst_complex = Node(4)

non_bst_complex.left = Node(2)
non_bst_complex.left.left = Node(1)
non_bst_complex.left.right = Node(3)
non_bst_complex.left.right.left = Node(1)
#non_bst_complex.left.right.right = Node(6)
from binarytree import bst

root = bst(height=3, is_perfect=False)
print('BST of default height: ', root)

root2 = bst(height=5, is_perfect=True)
print('BST of height 5 and perfect: ', root2)
Example #16
0
# @Rexhino_Kovaci
# balanced search tree is balanced if the difference between the height of the right and left subtrees is 1 or 0.
# in this implementation I've imported bst from the binarytree.py libray

from binarytree import bst

root = bst()
print('BST of any height : \n', root)

root2 = bst(height=3)
print('BST of given height : \n', root2)

root3 = bst(height=3, is_perfect=True)
print('Perfect BST of given height : \n', root3)
Example #17
0
def ejercicio_c():
    arbol = binarytree.bst(height=5, is_perfect=False)
    print(arbol, '\n')

    print('La profundidad del arbol es: ', arbol.height + 1,
          '\n')  # Sumamos 1 porque contamos la profundidad desde 1
Example #18
0
from binarytree import tree, bst

my_tree = bst(height=2, is_perfect=True)

print(my_tree)

print("Inorder Traversel -->")
print(my_tree.inorder)

print("Preorder Traversel -->")
print(my_tree.preorder)

print("Postoder Traversel -->")
print(my_tree.postorder)
Example #19
0
def ejercicio_b():
    arbol = binarytree.bst(height=3, is_perfect=False)
    print(arbol, '\n')

    print('El numero de nodos es: ', arbol.size, '\n')
def main():
    from binarytree import tree, bst, heap  # https://pypi.org/project/binarytree/
    root = bst(height=3)
    print(root)
    print(findNumberOfRights(root))
Example #21
0
            s += f" -> {r.value}"
        s += "]"
        return s


def list_of_depths(root: Node, list_starts=None, list_ends=None, depth=-0):
    if root:
        my_depth = depth + 1
        if not list_starts:
            list_starts = {}
        if not list_ends:
            list_ends = {}
        if my_depth not in list_starts:
            list_starts[my_depth] = list_ends[my_depth] = LNode(root.value)
        else:
            list_ends[my_depth].next = LNode(root.value)
            list_ends[my_depth] = list_ends[my_depth].next

        children = [root.left, root.right]
        for child in children:
            list_of_depths(child, list_starts=list_starts, list_ends=list_ends, depth=my_depth)

        return list_starts


if __name__ == "__main__":
    tree = bst(4)
    print(tree)
    answer = list_of_depths(tree)
    print(answer)
Example #22
0
from binarytree import Node, tree, bst, heap, pprint

# Generate a random binary tree and return its root
my_tree = tree(height=5, balanced=True)

# Generate a random BST and return its root
my_bst = bst(height=5)

# Generate a random max heap and return its root
my_heap = heap(height=3, max=True)

# Pretty print the trees in stdout
#pprint(my_tree)
#pprint(my_bst)
#pprint(my_heap)

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
pprint(root)
Example #23
0
from binarytree import bst


# ok here is a quick question how do you do this with out using huge amounts
# memory?
# o(n^2) is the algothirimic speed.
def printBinaryTreeLevelWise(Tree):
    currentLevel = 0
    # 0 is root and number bigger is closer to the leaves
    maxLevel = Tree.height
    while currentLevel <= maxLevel:
        subPrintBinaryTree(Tree, currentLevel, 0)
        currentLevel += 1


def subPrintBinaryTree(Node, levelToProcess, currentLevel):
    if levelToProcess == currentLevel:
        if hasattr(Node, 'value'):
            print(Node.value, ", ")
    else:
        subPrintBinaryTree(Node.left, levelToProcess, currentLevel + 1)
        subPrintBinaryTree(Node.right, levelToProcess, currentLevel + 1)

        # do nothing


if __name__ == "__main__":
    Tree = bst(height=4, is_perfect=True)
    print(printBinaryTreeLevelWise(Tree))
    print(Tree)
Example #24
0
            while cur != None:
                if node.value <= cur.value:
                    prev = cur
                    cur = cur.left
                else:
                    prev = cur
                    cur = cur.right
            if node.value <= prev.value:
                prev.left = node
            else:
                prev.right = node


if __name__ == "__main__":
    n = int(input("what is height of tree?"))
    head1 = bst(n)
    pprint(head1)
    size = int(input("Enter the number of elements to create a subtree"))
    subt = BStree()
    for i in range(size):
        val = int(input("enter the node %d value" % (i + 1)))
        subt.insert(Node(val))

    print("The input sub stree is")
    pprint(subt.root)
    if is_sub_tree(head1, subt.root):
        print("The tree headed %d is sub tree of the tree headed %d" %
              (subt.root.value, head1.value))
    else:
        print("The tree headed %d is NOT a sub tree of the tree headed %d" %
              (subt.root.value, head1.value))
Example #25
0
def main():
    from binarytree import tree, bst, heap  # https://pypi.org/project/binarytree/
    root = bst(height=3, is_perfect=True)
    print(root)
    print(checkAnswer(findMaxNodeOfBST(root), root.max_node_value))
Example #26
0
                if depth < mindepth:
                    mindepth = depth
        return mindepth


def minDepth(A):
    q = deque()
    q.append(A)
    curr, nest, level = 1, 0, 1
    while q:
        item = q.popleft()
        curr -= 1
        if not item.right and not item.left:
            return level
        if item.right:
            q.append(item.right)
            nest += 1
        if item.left:
            q.append(item.left)
            nest += 1
        if curr == 0:
            curr, nest = nest, curr
            level += 1


a = bst()
print(a)
#a= {3, 1, -1, -1}
print(minDepth(a))
b = heap()
print(b)
Example #27
0
# Problem: Given a target integer find the closest number in the BST

# DO: pip install binarytree
from binarytree import bst

target = 10
closest = float("inf")
tree = bst()  #generates random binary trees
print(" -generate a random tree from python lib -")
print(tree)


# Solution 1
# On Average: time O(logn), space O(1)
# Worst Case: time O(n), soace O(n)
def findClosestValueInBst(tree, target, closest):
    while tree is not None:
        if abs(target - closest) > abs(target - tree.value):
            closest = tree.value
        if target < tree.value:
            tree = tree.left
        elif target > tree.value:
            tree = tree.right
        else:
            break
    return closest


print(findClosestValueInBst(tree, target, closest))

Example #28
0
    def rebuildTree(self, inorder, preorder):
        if not inorder: return None

        root = inorder.index(preorder[0])
        l = self.rebuildTree(
            inorder[:root],
            preorder[1:root + 1],
        )
        r = self.rebuildTree(
            inorder[root + 1:],
            preorder[root + 1:],
        )

        cur = Node(preorder[0])
        cur.left, cur.right = l, r

        return cur


if __name__ == "__main__":
    obj = Solution()

    from binarytree import bst
    import random
    height = random.randint(3, 4)
    root = bst(height=height)
    obj = Solution()
    ino, preo, posto = root.inorder, root.preorder, root.postorder

    print(obj.rebuildTree([i.value for i in ino], [i.value for i in preo]))
    print("expected: %s" % root)
Example #29
0
        return 0

    runningSum += tree.value
    if tree.left is None and tree.right is None:
        sums.append(runningSum)

    getBranchSums(tree.left, runningSum, sums)
    getBranchSums(tree.right, runningSum, sums)


def nodeDepth(tree):
    return getDepthSum(tree, 0)


def getDepthSum(tree, depth):
    if tree is None:
        return 0

    return getDepthSum(tree.left, depth + 1) + getDepthSum(
        tree.right, depth + 1) + depth


# print(twoPointers([1, 2, 4, 6, 3, 9, -1], 12))
# print(validateSubsequence([5, 1, 22, 25, 6, -1, 8, 10], [1, 6, -1, 10]))
myTree = bst(2, True)
print(myTree)
# print(findClosest(myTree, -112))
# print(branchSums(myTree))

print(nodeDepth(myTree))
Example #30
0
#-*- coding:utf-8
class Solution(object):
    def mirror(self, root):
        if not root: return None

        root.left, root.right = self.mirror(root.right), self.mirror(root.left)
        return root


if __name__ == "__main__":
    from binarytree import bst
    import random
    root = bst(height=3)
    obj = Solution()
    nodes = root.inorder
    del_nodes = [n.value for n in random.sample(nodes, random.randint(2, 4))]
    print(root)
    print(obj.mirror(root))
Example #31
0
from binarytree import tree, bst, heap

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def lowestCommonAncestor(root, p, q):
    """
    :type root: TreeNode
    :type p: TreeNode
    :type q: TreeNode
    :rtype: TreeNode
    """
    if root in (None, p, q): return root
    left, right = (lowestCommonAncestor(kid, p, q)
                   for kid in (root.left, root.right))
    return right if left is None else left if right is None else root


# Generate a random binary tree and return its root node
my_tree = tree(height=3, is_perfect=False)

# Generate a random BST and return its root node
my_bst = bst(height=3, is_perfect=True)

print(my_tree)

print(lowestCommonAncestor(my_tree, my_tree.left.left, my_tree.left.right))