I expect the root node, which is 6 to be printed out. However, the output is None. Below is the code:
class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def __str__(self):
return str(self.key)
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self,key):
self.root = self._insert(self.root, key)
def _insert(self, node, key):
if node is None:
return TreeNode(key)
if key < node.key:
node.left = self._insert(node.left, key)
elif key > node.key:
node.right = self._insert(node.right, key)
return node
tree = BinarySearchTree()
tree.insert(6)
print(tree.insert(8))
Output: None
I have tried to change the return node to print(node) and print(tree.insert(8)) to tree.insert(8). After the change made, it printed out 6 as output. However, when back at the original code, I can't figure out why None is the output instead of 6 even after several hours of cracking my head.
Even though your
_insertmethod returns a node, yourinsertmethod doesn't return anything, so it defaults toNone.The bottom line is that you should not print what
insertreturns, and accept that it returnsNone: that is actually a good thing. If you would changeinsertto return the root node, that would not seem very useful.