Reputation: 137
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()
Upvotes: 0
Views: 74
Reputation: 1339
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
Upvotes: 1