binary search tree in python

bst.py
--------


class Node:
    def __init__(self,val):
        self.value=val
        self.leftchild=None
        self.rightchild=None
    def insert(self,data):
        if self.value== data:
            return False
        elif self.value>data:
            if self.leftchild:
                return self.leftchild.insert(data)
            else:
                self.leftchld = Node(data)
                return True
        else:
            if self.rightchild:
                return self.rightchild.insert(data)
            else:
                self.rightchild = Node(data)
                return True
    def find(self,data):
        if(self.value == data):
            return True
        elif self.value>data:
            if self.leftchild:
                return self.leftchild.find(data)
            else:
                self.leftchild=Node(data)
                return False
        else:
            if self.rightchild:
                return self.rightchild.find(data)
            else:
                self.rightchild = Node(data)
                return False
   
    def preorder(self):
        if self:
            print (str(self.value))
            if self.leftchild:
                self.leftchild.preorder()
            if self.rightchild:
                self.rightchild.preorder()
             

    def postorder(self):
        if self:
            if self.leftchild:
                self.leftchild.postorder()
            if self.rightchild:
                self.rightchild.postorder()
            print (str(self.value))


    def inorder(self):
        if self:
            if self.leftchild:
                self.leftchild.inorder()
            print (str(self.value))

            if self.rightchild:
                self.rightchild.inorder()

class Tree:
    def __init__(self):
        self.root=None

    def insert(self,data):
        if self.root:
            return self.root.insert(data)
        else:
            self.root=Node(data)
            return True
       
    def find(self,data):
        if self.root:
            return self.root.find(data)
        else:
            return False

    def preorder(self):
        print("PreOrder")
        self.root.preorder()

    def postorder(self):
        print("PostOrder")
        self.root.postorder()

    def inorder(self):
        print("inOrder")
        self.root.inorder()

pyton shell

>>> from bst import Tree
>>> bst=Tree()
>>> bst.insert(10)
True
>>> bst
<bst.Tree instance at 0x02B42698>
>>> print bst
<bst.Tree instance at 0x02B42698>
>>> bst.insert(14)
True
>>> bst.preorder()
PreOrder
10
14
>>> bst.postorder()
PostOrder
14
10
>>> bst.inorder()
inOrder
10
14
>>>

No comments:

Post a Comment