Printing the result of insertion of a Binary Search Tree

39 Views Asked by At

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.

2

There are 2 best solutions below

0
trincot On

Even though your _insert method returns a node, your insert method doesn't return anything, so it defaults to None.

The bottom line is that you should not print what insert returns, and accept that it returns None: that is actually a good thing. If you would change insert to return the root node, that would not seem very useful.

0
chandrahaas reddy bhumireddy On

The reason you're getting None as output when you call print(tree.insert(8)) is because the insert method returns None when it's not explicitly returning a new node. In the case where you're calling tree.insert(8), the method is called for insertion, but it returns None because it doesn't explicitly return anything when the insertion happens. Hence, when you print the result of tree.insert(8), you get None.But when iterate through the tree 6 and 8 will be printed.

tree = BinarySearchTree()

tree.insert(6)

tree.insert(8)