I just learned how to create Binary Search Trees in C#. I decided to try to code the same thing in Python 3.x. However, when I got to my Print method, this error showed up:
Traceback (most recent call last):
File "C:\Users\danie\Desktop\Python\BinarySearchTree\BinarySearchTree\BinarySearchTree.py", line 62, in <module>
b.BSTprint()
File "C:\Users\danie\Desktop\Python\BinarySearchTree\BinarySearchTree\BinarySearchTree.py", line 46, in BSTprint
BST.Print(current)
TypeError: Print() missing 1 required positional argument: 'cur'
The problem, I did put in the required positional argument. I tried fixing it myself and found that if I remove the self parameter, it works. However, I always thought you needed to have that self parameter in all of the class methods. I have no idea what is wrong. Here is the code
import random
class BST:
#Node class
class Node:
data = None
left = None
right = None
def __init__(self, d):
self.data = d
first = None
#Add method
def Add(self, d):
#Checks if the Binary Search Tree is empty
if(BST.first == None):
BST.first = BST.Node(d)
#Debugging purposes
#print("Added: {}".format(d))
return;
else:
newNode = BST.Node(d)
cur = BST.first
while(cur != None):
if(cur.data < newNode.data):
if(cur.left == None):
cur.left = newNode
#print("Added: {}".format(newNode.data))
return
else:
cur = cur.left
elif(cur.data > newNode.data):
if(cur.right == None):
cur.right = newNode
#print("Added: {}".format(newNode.data))
return
else:
cur = cur.right
else:
print("Value already in BST")
return
def BSTprint(self):
current = BST.first
if(current == None):
return
BST.Print(current)
def Print(self, cur):
if(cur.left != None):
BST.Print(cur.left)
print(cur.data)
if(cur.right != None):
BST.Print(cur.right)
b = BST()
#Adds values into BST
for i in range(10):
x = random.randint(1,100)
b.Add(x)
b.BSTprint()