Search code examples
pythongraphbinary-treenodes

Printing binary tree after initialising gives None value


I have a simple binary tree. I have intialized it using TreeNode class, but while printing out the values from the tree, it gives me None value as well. How to mitigate this?

The code snippet is as follows:

class TreeNode:
    def __init__(self, root=None, left = None, right= None):
        self.value = root
        self.left = left
        self.right = right

def tree(root) -> int:
    # print(root)

    if root is not None:
        print(root.value)
        print(tree(root.left))
        print(tree(root.right))
    return None

root = TreeNode(1)
# root.value = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)

tree(root)

The above code gives the following output:

1
2
None
None
None
3
None
None
None

While I want only to print 1 2 3 without printing the None values. How can we achieve this??


Solution

  • All you have to do is to remove the print in your function call.

    The None output exists because you are printing the result of your function call. So even if the result of a function doesn't have any value, you are still forcing the tree function to have an output, then out goes the None output you are talking about. So the code should be like this:

    def tree(root) -> int:
        # print(root)
    
        if root is not None:
            print(root.value)
            tree(root.left)
            tree(root.right)
        return
    

    Output:

    1
    2
    3
    

    To have a better understanding please take a look on this similar question.