0

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'
asked Jun 29, 2020 at 15:14
1
  • self.left.exists is not in your code. Did you mean self.left.is_exist() ? Commented Jun 29, 2020 at 15:21

1 Answer 1

1

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)

answered Jun 29, 2020 at 15:21
Sign up to request clarification or add additional context in comments.

2 Comments

sorry its changes with all my testing... but is still dont work.
Sorry, I missed your second problem. I edited my answer.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.