0

I have a theoretical question and as well small mistake, so I am calling inorder_traversal function which was supposed to order the binary tree an it gives me an error inorder_traversal() takes 0 positional arguments but 1 was given. I gave zero arguments and I called zero arguments. So that is the first question and the second one ism so this inorder_traversal function, how does it go from the furthest left up. I didn't quite catch that last part?

class BinarySearchTree:
 def __init__(self, value):
 self.left = None
 self.right = None
 self.value = value
 
 def insert(self, value):
 #checking if value that we are trying to insert is less then the current value
 if value < self.value:
 if self.left is None:
 #if the left node is not existing then we are going to create it
 self.left = BinarySearchTree(value)
 else:
 self.left.insert(value)
 else:
 if self.right is None:
 self.right = BinarySearchTree(value)
 else:
 self.right.insert(value)
 def inorder_traversal():
 if self.left:
 self.left.inorder_traversal()
 print(self.value)
 if self.right:
 self.right.inorder_traversal()
 
 
tree = BinarySearchTree(15)
tree.insert(14)
tree.insert(20)
tree.insert(7)
tree.insert(8)
tree.insert(1)
tree.insert(70)
tree.inorder_traversal()
asked Oct 6, 2022 at 13:29
1
  • 1
    inorder_traversal should probably be an instance method. As such you need to write def inorder_traversal(self): (notice the self argument). Commented Oct 6, 2022 at 13:32

1 Answer 1

1

For the first question the answer is that if you called an instance method in python then a self object is passed as an argument to the function so you need to include that parameter in your class function:

def inorder_traversal(self):

This line:

tree.inorder_traversal()

Is equivalent to:

BinarySearchTree.inorder_traversal(tree)

And for the second question you can see this video on youtube it explains the different traversal ordering of binary trees: https://www.youtube.com/watch?v=-b2lciNd2L4

answered Oct 6, 2022 at 13:32
Sign up to request clarification or add additional context in comments.

Comments

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.