Random Binary Tree Generator using Python

Generating random binary tree using Python having elements (numbers, primes, alphabets)

Initialize Node for binary tree

Binary tree is created with insertion at end process.

class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

class BT:
    def __init__(self):
        self.root = None
    
    def insert(self, val):
        if not self.root:
            self.root = Node(val)
            return

        q = []
        q.append(self.root)
        while len(q):
            temp = q[0]
            q.pop(0)

            if not temp.left:
                temp.left = Node(val)
                break
            q.append(temp.left)
            
            if not temp.right:
                temp.right = Node(val)
                break
            q.append(temp.right)

random => start to end

randBT() takes parameters start (starting number), end (ending number) and count (number of nodes in the binary tree, default 1). This function generates a binary tree consist of random numbers from start to end (both start and end included) with length of count and returns the root of the binary tree.

def randBT(start:int, end:int, count:int = 1):
    bt = BT()
    for _ in range(count):
        rval = random.randint(start,end)
        bt.insert(rval)
    return bt.root

random odd => start to end

randOddBT() takes parameters start (starting number), end (ending number) and count (number of elements in the binary tree, default 1). This function generates a doubly binary tree consist of random odd numbers from start to end (both start and end included) with length of count and returns the root of the binary tree.

def randOddBT(start:int, end:int, count:int = 1):
    bt = BT()
    while count>0:
        rval = random.randint(start,end)
        if rval%2!=0:
            bt.insert(rval)
            count-=1
    return bt.root

random even => start to end

randEvenBT() takes parameters start (starting number), end (ending number) and count (number of elements in the binary tree, default 1). This function generates a binary tree consist of random even numbers from start to end (both start and end included) with length of count and returns the root of the binary tree.

def randEvenBT(start:int, end:int, count:int = 1):
    bt = BT()
    while count>0:
        rval = random.randint(start,end)
        if rval%2==0:
            bt.insert(rval)
            count-=1
    return bt.root

random => PRIME

randPrime() takes parameters start (starting number), end (ending number) and count (number of elements in the binary tree, default 1). This function generates a binary tree consist of random prime numbers from start to end (both start and end included) with length of count and returns the root of the binary tree.

def isPrime(n:int):
    if n<=3 and n>1:
        return 1
    if n%2==0 or n%3==0:
        return 0
    i=5
    while i*i<n:
        if n%i==0 or n%(i+2)==0:
            return False
        i+=6
    return True

def randPrimeBT(start:int, end:int, count:int = 1):
    arr = []
    bt = BT()
    for i in range(start,end+1):
        pval = i
        if pval<0:
            pval*=-1
        if isPrime(pval):
            arr.append(i)
    for _ in range(count):
        rval = random.choice(arr)
        bt.insert(rval)
    return bt.root

random => alphabets (uppercase, lowercase, both uppercase and lowercase)

randAlphaBT() takes parameters type (type of alphabet), count (number of elements in the binary tree, default 1). This function generates a binary tree consist of random alphabets with length of count and returns the root of the binary tree. Parameter type takes 3 types of values (“UPPER”, “LOWER”, “MIXED”). “UPPER” for only upper case alphabets. “LOWER” for only lower case alphabets. “MIXED” for both upper and lower case alphabets.

def randAlphaBT(type:str, count:int = 1):
    LCASE = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    bt = BT()
    l=[]
    if type == "UPPER":
        for _ in range(count):
            rval = random.choice(LCASE).upper()
            bt.insert(rval)
            l.append(rval)
    elif type == "LOWER":
        for _ in range(count):
            rval = random.choice(LCASE)
            bt.insert(rval)
            l.append(rval)
    elif type == "MIXED":
        for _ in range(count):
            rval = random.choice(LCASE)
            if random.choice([True,False]):
                rval = rval.upper()
            bt.insert(rval)
            l.append(rval)
    return bt.root

Example

import randomBinaryTree

def inorder(temp):
    if (not temp):
        return
    inorder(temp.left)
    print(temp.val,end = " ")
    inorder(temp.right)

headRand = randomBinaryTree.randBT(1, 10, 5)
headRandOdd = randomBinaryTree.randOddBT(1, 20, 5)
headRandEven = randomBinaryTree.randEvenBT(1, 20, 5)
headRandPrime = randomBinaryTree.randPrimeBT(1, 20, 5)
headRandUpper = randomBinaryTree.randAlphaBT("UPPER", 10);
headRandLower = randomBinaryTree.randAlphaBT("LOWER", 10);
headRandMixed = randomBinaryTree.randAlphaBT("MIXED", 10);

print("Random Binary Tree")
inorder(headRand)
print("\nRandom Binary Tree - Odd")
inorder(headRandOdd)
print("\nRandom Binary Tree - Even")
inorder(headRandEven)
print("\nRandom Binary Tree - Prime")
inorder(headRandPrime)
print("\nRandom Binary Tree - Uppercase")
inorder(headRandUpper)
print("\nRandom Binary Tree - Lowercase")
inorder(headRandLower)
print("\nRandom Binary Tree - both Uppercase and Lowercase")
inorder(headRandMixed)

Output

Random Binary Tree
1 1 6 1 5
Random Binary Tree - Odd
7 1 19 15 11
Random Binary Tree - Even
18 16 2 16 4
Random Binary Tree - Prime
5 1 7 3 5
Random Binary Tree - Uppercase
S A B R F M E C T M
Random Binary Tree - Lowercase
u i f x x z l c l s
Random Binary Tree - both Uppercase and Lowercase
X X b H A e U P B G

Leave a Reply

Your email address will not be published.