I have implemented a simple tree and I have this problem. When I try to search for a node and it exists it returns None even though it runs the print at the if statement in lookup method. It runs ok when I lookup for the root node. All the rest nodes return None. Could someone explain why ?
class Node():
def __init__(self,data):
self.right = None
self.left = None
self.data = data
def insert(self,data):
if self.data == data:
print "this item exists"
elif self.data > data:
if self.left == None:
self.left = Node(data)
else:
self.left.insert(data)
else:
if self.right == None:
self.right = Node(data)
else:
self.right.insert(data)
def print_nodes(self):
if self.left:
self.left.print_nodes()
print self.data
if self.right:
self.right.print_nodes()
def lookup(self,data):
if self.data == data:
print 'exists'
return 1
elif self.data > data:
if self.left != None:
self.left.lookup(data)
else:
return -1
elif self.data < data:
if self.right != None:
self.right.lookup(data)
else:
return -1
def delete(self,data):
if self.lookup(data)== -1:
print "doesnot exists"
else:
if (not self.left) and (not self.right):
self.data = None
root = Node(5)
#root.insert(3)
root.insert(3)
root.insert(2)
root.insert(6)
root.insert(61)
root.insert(62)
root.insert(63)
x = root.lookup(3)
print x