2

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
1
  • 1
    You're not returning the results from the recursive calls to lookup. Commented Dec 7, 2014 at 13:20

1 Answer 1

3

when the item is not exists in the root, you call to its sons lookup() functions without returning their value, so even if the code finds the data somewhere in the tree, you get None value instead of the result (1/-1)

Replace this lines:

self.left.lookup(data)
...
self.right.lookup(data)

with the lines:

return self.left.lookup(data)
...
return self.right.lookup(data)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.