My python function for find is returning None object though it is finding the key accurately
Question:
I am writing a code to find Node with a particular key in a binary tree, though it is finding the Node correctly but returning None
def Find(key,root):
if(root):
if (key>root.key):
print("going right")
Find(key,root.right)
elif (key<root.key):
print("going left")
Find(key,root.left)
elif (key == root.key):
print("found" )
print(root)
return root
else :
print("not in the tree")
return 0
temp = Find(5, bt.root) //Find the node with key 5 in the tree
print(type(temp))
// Output >>
<__main__.Node object at 0x000000F8A7DCAAC8>
<class 'NoneType>
Why it is returning None type as the function is clearly returning node
Answers:
Change Find(key,root.right)
to return Find(key,root.right)
(similarly for left).
Currently, when you are finding the element, you are not returning it, so the function implicitly returns None
.
I am writing a code to find Node with a particular key in a binary tree, though it is finding the Node correctly but returning None
def Find(key,root):
if(root):
if (key>root.key):
print("going right")
Find(key,root.right)
elif (key<root.key):
print("going left")
Find(key,root.left)
elif (key == root.key):
print("found" )
print(root)
return root
else :
print("not in the tree")
return 0
temp = Find(5, bt.root) //Find the node with key 5 in the tree
print(type(temp))
// Output >>
<__main__.Node object at 0x000000F8A7DCAAC8>
<class 'NoneType>
Why it is returning None type as the function is clearly returning node
Change Find(key,root.right)
to return Find(key,root.right)
(similarly for left).
Currently, when you are finding the element, you are not returning it, so the function implicitly returns None
.