0
votes

I'm having trouble to search in the binary tree, i want to check if the root is exists but encountered an error. What am I doing wrong?

this is my full code:

class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    def printTree(self):
        if self.left:
            self.left.PrintTree()
        print(self.data),
        if self.right:
            self.right.PrintTree()

    def insert(self, data):
        """ Compare the new value with the parent node """
        if self.data:
            if data < self.data:
                if self.left is None:
                    self.left = Node(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Node(data)
                else:
                    self.right.insert(data)
        else:
            self.data = data

    def is_exist(self, val):
        if val < self.data:
            if self.left is None:
                return None, None
            return self.left.exists(val, self)
        elif val > self.data:
            if self.right is None:
                return None, None
            return self.right.exists(val, self)
        else:
            return self.data

this is my search function to check if root is exist

def is_exist(self, val): if val < self.data: if self.left is None: return None, None return self.left.exists(val, self) elif val > self.data: if self.right is None: return None, None return self.right.exists(val, self) else: return self.data

this is the test:

def test_binary_tree():
    root = Node(10)
    assert root.is_exist(10)
    root.insert(4)
    assert root.is_exist(4)
    root.insert(11)
    assert root.is_exist(11)
    root.insert(3)
    assert root.is_exist(3)
    root.insert(770)
    assert root.is_exist(770)
    root.insert(523)
    assert root.is_exist(523)
    root.insert(43)

print(test_binary_tree())

the eror i got:

    return self.left.exists(val, self)
AttributeError: 'Node' object has no attribute 'exists'
1
self.left.exists is not in your code. Did you mean self.left.is_exist() ?Ronald

1 Answers

1
votes

You call your function by the wrong name. Also, one doesn't specify the self if you call an object's methods. See here. You wrote return self.right.exists(val, self) but you should have written return self.right.is_exist(val)