Python DFS

  • 0
    class Solution(object):
        def pathSum(self, root, sum):
            ans = []
            def dfs(r, tmp, s):
                if not r:
                if not r.left and not r.right:
                    if s == sum:
                if r.left:
                    dfs(r.left, tmp + [r.left.val], s + r.left.val)
                if r.right:
                    dfs(r.right, tmp + [r.right.val], s + r.right.val)
            if not root:
                return []
            dfs(root, [root.val], root.val)
            return ans

Log in to reply

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