Pass a value by reference in a function to find level of node in a binary tree

168 Views Asked by At

I am trying to write a function to find the level of a node in a binary tree. Here is my implementation:

def level_of_node(root, node, level):
    if root is None:
        return -1

    if root.data == node:
        return level

    return level_of_node(root.left, node, level+1)
    return level_of_node(root.right, node, level+1)

Here is my tree:

root = Node(6)
root.left = Node(10)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(30)
root.left.right.left = Node(16)
root.left.right.right = Node(8)
root.right.right = Node(3)
root.right.left = Node(5)

level = 0
x = level_of_node(root, 16, level)
print x

When i call this function, it should return the level of node but it returns -1.

I think it is because level is passed by value. Can anyone suggest me better way to do it recursively ?

0

There are 0 best solutions below