美文网首页
113. Path Sum II

113. Path Sum II

作者: xiaoyaook | 来源:发表于2017-11-11 21:28 被阅读0次

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

    经典的DFS题目,
    重点就是dfs函数中的cur和res参数,利用cur不断保存当前路径上的参数,利用res保存符合题目的数组

    class Solution(object):
        def pathSum(self, root, sum):
            if not root:
                return []
            res = []
            self.dfs(root, sum, [], res)
            return res
        
        def dfs(self, root, sum, cur, res):
            if not root.left and not root.right and sum == root.val:
                cur.append(root.val)
                res.append(cur)
            if root.left:
                self.dfs(root.left, sum-root.val, cur+[root.val], res)
            if root.right:
                self.dfs(root.right, sum-root.val, cur+[root.val], res)
    

    相关文章

      网友评论

          本文标题:113. Path Sum II

          本文链接:https://www.haomeiwen.com/subject/qkegmxtx.html