DFS recurion method of python


  • 0
    class Solution(object):
        def pathSum(self, root, sum):
            if not root:
                return []
            res,stack=[],[root.val]
            def dfs(node,sum):
                if not node.left and not node.right:
                    if sum==0:
                        res.append(stack[:])
                    return res
                if node.left:
                    stack.append(node.left.val)
                    dfs(node.left,sum-node.left.val)
                    stack.pop()
                if node.right:
                    stack.append(node.right.val)
                    dfs(node.right,sum-node.right.val)
                    stack.pop()
            dfs(root,sum-root.val)
            return res
                
    

Log in to reply
 

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