python program to Implement Binary Tree and its traversals.

in this tutorial we are learn about binary tree and binary tree traversal 

in the binary tree each node having only two child node , binary tree are not having more then two nodes .
binary tree traversal is a traveling each and every nodes in the tree , visiting each and every nodes of the tree 

binary tree and binary tree traversal

code:

class Node:

    def __init__(self,data):

        self.data=data

        self.left=None

        self.right=None

 

class BST:

    def __init__(self):

        self.root=None

    def insert(self,data):

        newnode=Node(data)

        if(self.root==None):

            self.root=newnode

            print("node successfully inserted as root")

        else:

            temp=self.root

            while(temp is not None):

                par=temp

                if(temp.data>data):

                    temp=temp.left

                else:

                    temp=temp.right

            if(data>par.data):

                par.right=newnode

            else:

                par.left=newnode

            print("Node inserted successfully")

    def inorder(self,temp):

        if(temp is not None):

            self.inorder(temp.left)

            print(temp.data,end=" ")

            self.inorder(temp.right)

    def preorder(self,temp):

        if(temp is not None):

            print(temp.data,end="")

            self.preorder(temp.left)

            self.preorder(temp.right)

    def postorder(self,temp):

        if(temp is not None):

             self.postorder(temp.left)

             self.postorder(temp.right)

             print(temp.data,end="")

    def findmin(self):

        temp=self.root

        while(temp.left is not None):

            temp=temp.left

        print("The minimum value in the binary search tree is",temp.data)

    def findmax(self):

        temp=self.root

        while(temp.right is not None):

            temp=temp.right

        print("The maximum value in the binary search tree is",temp.data)

 

tree=BST()

print("Menu")

choice=int(input("1.Insert \t2.Delete \t3.Display Inorder \t4.Display Preorder t5.Dispay Postorder \t6.Display minimum \t7.Display maximum"))

while choice is not 8:

    if choice is 1:

        val=int(input("Enter data to be inserted"))

        tree.insert(val)

    elif choice is 2:

        val=int(input("Enter node you want to delete"))

        root=tree.delete(tree.root,val)

    elif choice is 3:

        tree.inorder(tree.root)

    elif choice is 4:

        tree.preorder(tree.root)

    elif choice is 5:

        tree.postorder(tree.root)

    elif choice is 6:

        tree.findmin()

    elif choice is 7:

        tree.findmax()

    choice=int(input("Enter your choice again"))

        

o/p:-

Binary Tree and its traversals.
Binary Tree and its traversals.

Post a Comment

0 Comments