global nodeM
nodeM=None
def inorderTraversal(self, root: 'TreeNode', tval:int) -> 'TreeNode':
#if(nodeM):
#print("sdf", type(nodeM))
#node=None
if root:
self.inorderTraversal(root.left,tval)
print(root.val)
if(root.val==tval):
#print("root = ",root)
nodeM=root
print("node = ", nodeM)
print("my MAN,", type(nodeM))
return nodeM
return #node
#inorderTraversal(root.left,tval)
self.inorderTraversal(root.right,tval)
return
This is the code every time I try to return the node. If it's the root, it works, otherwise it returns null-none. The problem is find the node with tval, it exist for sure.
There are a few issues:
Although you have a
return nodeM, you ignore this returned value when a recursive call has been made. You haveself.inorderTraversal(root.left,tval), but don't do anything with what this call returns, yet that return could be the node that was found. The same goes forself.inorderTraversal(root.right,tval)Using a global variable is not helping, as there is no code that ever reads that value of
nodeM(apart from printing it). Moreover, it is only set toNoneonce, so that if you have multiple tree traversals,nodeMmight still have a node reference from a previously iterated tree. So just don't use a global variable. It is not needed.Corrected code with comments where changes were made:
You could do this with one
returnexpression too:One more remark: in the title of your post you mention "BST". This is confusing, because a full traversal is only necessary if your tree is just any binary tree, not necessarily a BST. If however your tree is a BST, then you should not perform an inorder traversal. The idea of a BST is that you have a faster way to find a node, and you don't have to look both left and right, but only go one way. If in fact you wanted to search a BST, then check out Search in a Binary Search Tree