I am trying to implement a Binary Search Tree in python to practice recursion skills, but my head
variable isn't updating on the first call to add()
. It continues to stay at a null value even though it should be updated on the first call as it is the currentNode
. What am I doing wrong?
class BinarySearchTree:
class Node:
def __init__(self, data):
self.data = data
self.Right = None
self.Left = None
head = None
def __init__(self):
self.head = None
def add(self, newNode):
self.__addrecursive(self.head, newNode)
def __addrecursive(self, currentNode, valueToAdd):
if currentNode is None:
currentNode = self.Node(valueToAdd)
return currentNode
elif valueToAdd < currentNode.data:
return self.__addrecursive(self, currentNode.Left, valueToAdd)
else:
return self.__addrecursive(self, currentNode.Right, valueToAdd)
import BinarySearchTree as treelib
tree = treelib.BinarySearchTree()
tree.add("Apple")
print(tree.head) #Head should contain "Apple" but is intead None
I have made a few changes to your code.
head = None
which is never usedself.head =
inside the add function becaues previously __addrecursive was returning a node but it wasn't being assigned to anythingclass BinarySearchTree:
class Node:
def __init__(self, data):
self.data = data
self.Right = None
self.Left = None
def __init__(self):
self.head = None
def add(self, newNode):
self.head = self.__addrecursive(self.head, newNode)
def __addrecursive(self, currentNode, valueToAdd):
if currentNode is None:
return self.Node(valueToAdd)
elif valueToAdd < currentNode.data:
currentNode.Left = self.__addrecursive(currentNode.Left, valueToAdd)
else:
currentNode.Right = self.__addrecursive(currentNode.Right, valueToAdd)
return currentNode
I don't really know about binary trees so I could be wrong because I just copied some code from here: https://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.