I am trying below problem but not sure what is the mistake. Variable res is not set properly. Please someone help
Given a binary tree with distinct nodes(no two nodes have the same data values). The problem is to print the path from root to a given node x. If node x is not present then print “No Path”.
Input : 1
/
2 3
/ \ /
4 5 6 7
x = 5Output : 1->2->5
'''
class getNode:
def init(self,val,left = None,right=None):
self.val = val
self.left = left
self.right = right
def printPath(root,k):
res = ""
def preorder(node,s):
#res
if not node:
return False
if node.val==k:
s += str(node.val)
res = s
return True
else:
s += str(node.val) + '->'
if preorder(node.left,s) or preorder(node.right,s):
return True
else:
return False
return res if preorder(root,'') else "No Path"
if name == 'main':
# binary tree formation
root = getNode(1)
root.left = getNode(2)
root.right = getNode(3)
root.left.left = getNode(4)
root.left.right = getNode(5)
root.right.left = getNode(6)
root.right.right = getNode(7)
x = 5
print(printPath(root, x))'''