DFS solution in Python

  • 0
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Solution(object):
        def pathSum(self, root, sum):
            :type root: TreeNode
            :type sum: int
            :rtype: List[List[int]]
            def find_path(node, remain, path, path_list):
                if node==None:  return
                if node.val==remain and node.left==None and node.right==None:  path_list.append(path+[node.val])
                find_path(node.left, remain-node.val, path+[node.val], path_list)
                find_path(node.right, remain-node.val, path+[node.val], path_list)
            res = []
            find_path(root, sum, [], res)
            return res

Log in to reply

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