Sunday, 5 January 2014

Python3 Binary tree implementation

Friends,

I am learning python (why? - read my last post). I implemented Binary tree in python3 and thought of sharing with you. Definitely, this is not the optimized version but I wanted to share what I have done.


class btree:
   
    def __init__(self):
        self.data = -1
        self.left = None
        self.right = None
      
    def searchItem(self, a_data):
      
        if (self == None):
            return None
        elif (self.data == a_data):
            return self
        elif (self.data > a_data):
            return searchItem(self.left, a_data)
        elif (self.data < a_data):
            return searchItem(self.right, a_data)

    def insertItem(self, a_data = 0):
          
        if (self.data == -1):
            self.data = a_data
          
        elif (self.data > a_data):
      
            if (self.left == None):
                other = btree()
                other.data = a_data
                self.left = other
                print("Inserted to Left of" + str(self.data))
            else:
                self.left.insertItem(a_data)
              
        elif (self.data < a_data):

            if (self.right == None):
                other = btree()
                other.data = a_data
                self.right = other
                print ("Inserted to Right" + str(self.data))
            else:
                self.right.insertItem(a_data)
      
    def printTree(self):
      
        if (self != None):
            if (self.left == None):
                pass
            else:
                self.left.printTree()
            print(self.data)
            if (self.right == None):
                pass
            else:
                self.right.printTree()
        else:
            pass
          
sample = btree()
choice = 0

while(choice != 3):
    try:
        choice = int(input("1.Insert to the tree 2. Print Tree 3.Exit the program"))
    except ValueError :
        print ("Please Enter valid values")
      
    if (choice == 1):
        a_data = float(input("Enter the data to be inserted in to the tree"))
        sample.insertItem(a_data)
    elif (choice == 2):
        sample.printTree()
    else:
        pass


Thanks,
Santhosh