My DFS solution and with a big lesson for pass-by-reference


  • 0
    M

    solution -- DFS LIFO
    class Solution(object):

    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        stack=[(root,0,[])]; ans=[]
        while stack and root:
            node,tot,path=stack.pop()
            tot+=node.val
            path+=node.val,
            if not node.left and not node.right: 
                if tot==sum: ans+=path[:],   ##note: python is pass-by reference so you have to use path[:] instead of path
            if node.left: 
                stack+=(node.left,tot,path[:]),  ##note: python is pass-by reference so you have to use path[:] instead of path
            if node.right: 
                stack+=(node.right,tot,path[:]),  ##note: python is pass-by reference so you have to use path[:] instead of path
        return ans

Log in to reply
 

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