Binary Tree Paths (Leetcode 257)

Technique: FAITH technique of Recursion

Problem Link: https://leetcode.com/problems/binary-tree-paths/

class Solution:

    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        global ans
        
        def fun(root):
            global ans
            ans=[]
            if(root is None):
                return ans  
            if(root.left is None and root.right is None):
                return [str(root.val)]
            lans=fun(root.left)
            rans=fun(root.right)
            if(lans != []):
                for i in range(len(lans)):
                    lans[i]=str(root.val)+"->"+lans[i]      
            if(rans != []):
                for i in range(len(rans)):
                    rans[i]=str(root.val)+"->"+rans[i]
            lans.extend(rans)
            return lans
        
        ans=fun(root)
        return ans

Last updated