Skip to content

Instantly share code, notes, and snippets.

@rupalbarman
Last active February 25, 2017 13:28
Show Gist options
  • Save rupalbarman/b29a56ceb15c132d9b964f242bcb8a8b to your computer and use it in GitHub Desktop.
Save rupalbarman/b29a56ceb15c132d9b964f242bcb8a8b to your computer and use it in GitHub Desktop.
Binary Search Tree in Python
'''
Binary Searc Tree Simple
Rupal Barman
[email protected]
This is a demonstration of implementing BST in python.
Since, it's basic. Feel free to add in more features.
'''
class Node(object):
count=0
def __init__(self, data, left= None, right= None):
self.data= data
self.left= left
self.right= right
Node.count+=1
class Tree(object):
def __init__(self):
self.root= None
def insert(self, data):
if self.root==None:
self.root= Node(data)
else:
curr= self.root
while True:
if data< curr.data:
if curr.left:
curr= curr.left
else:
curr.left= Node(data)
break
elif data> curr.data:
if curr.right:
curr= curr.right
else:
curr.right= Node(data)
break
def inorder(self, node):
if node!=None:
self.inorder(node.left)
print(node.data)
self.inorder(node.right)
if __name__=="__main__":
head= Tree()
head.insert(10)
head.insert(20)
head.insert(30)
head.insert(5)
head.inorder(head.root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment