What's wrong with my recursive Python method?


  • 0
    class Solution(object):
    lst = list()
    
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if root is None:
            return []
                
        def binaryTreePathsRecur(root, s):
            if root.left is None and root.right is None:
                self.lst.append(s)
            if root.left is not None:
                sl = s + "->" + str(root.left.val)
                binaryTreePathsRecur(root.left, sl)
            if root.right is not None:
                sr = s + "->" + str(root.right.val)
                binaryTreePathsRecur(root.right, sr) 
                
        s = str(root.val)
        binaryTreePathsRecur(root, s)
        return self.lst
    
            
    
    
    class Solution(object):
    
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if root is None:
            return []
    
        lst = list()        
        def binaryTreePathsRecur(root, s):
            if root.left is None and root.right is None:
                lst.append(s)
            if root.left is not None:
                sl = s + "->" + str(root.left.val)
                binaryTreePathsRecur(root.left, sl)
            if root.right is not None:
                sr = s + "->" + str(root.right.val)
                binaryTreePathsRecur(root.right, sr) 
                
        s = str(root.val)
        binaryTreePathsRecur(root, s)
        return lst
    

    The 2nd solution passed but the 1st failed, 1st shows "Input [1, 2], Output ['1', '1->2'], Expected ['1->2']", anyone knows why? I thought these two solutions are almost the same.


  • 1

    You can modify the first line

    lst = list()
    

    to:

    def __init__(self):
        self.lst = list()
    

    The reason may be related to how the OJ uses your method when judging.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.