Path to a Given node

Technique: FAITH technique of Recursion

Problem Link: https://www.interviewbit.com/old/problems/path-to-given-node/

class Solution:

    def solve(self, root, B):
        global ans
        ans=[]
        def func(root,B):
            
            global ans
            
            if(root is None):
                return False
            if(root.val == B):
                ans.append(root.val)
                return True
            leftans=func(root.left, B)
            if(leftans):
                ans.append(root.val)
                return True
            rightans=func(root.right, B)
            if(rightans):
                ans.append(root.val)
                return True
            return False
        func(root,B)
        return ans[::-1]

Last updated