美文网首页leetcode题解
【Leetcode】113—Path Sum II

【Leetcode】113—Path Sum II

作者: Gaoyt__ | 来源:发表于2019-07-17 00:05 被阅读0次
一、题目描述

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。

相关题目:leetcode112: Path Sum

二、代码实现
# 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 dfs(root, path, dist, res):
            if not root.left and not root.right:
                if dist + root.val == sum:
                    res.append((path + str(root.val)).split(','))
                
            if root.left:
                dfs(root.left, path + str(root.val) + ',', dist + root.val, res)
            
            if root.right:
                dfs(root.right, path + str(root.val) + ',', dist + root.val, res)
            
            
        if not root: return []
        res = []
        dfs(root, '', 0, res)
        return res

相关文章

网友评论

    本文标题:【Leetcode】113—Path Sum II

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