Saturday, June 2, 2018

Inserting of elements in Binary search tree with minimal tree creation in Python

class node:
    def __init__(self,val):
        self.value = val
        self.left = None        self.right = None
def insert_node(val,root):
    if(val<root.value):
        if(root.left is None):
            root.left = node(val)
        else:
            insert_node(val,root.left)

    else:
        if(root.right is None):
            root.right = node(val)
        else:
            insert_node(val,root.right)

def inorder(root):
    if(root):
        print(root.value)
        inorder(root.left)
        inorder(root.right)

def minimal_tree(arr,start,end):
    if(start>end):
        return None    mid = (start+end)//2    root = node(arr[mid])
    root.left = minimal_tree(arr,start,mid-1)
    root.right = minimal_tree(arr,mid+1,end)

    return root

root = node(3)

x= [5,4,1,2]
for i in x:
    insert_node(i,root)

inorder(root)
y = [1, 2, 3, 4, 5 ,6 ,7, 8,9]




test = minimal_tree(y,0,len(y)-1)
print(test.value)
inorder(test)

No comments:

Post a Comment