leetcode题解

【Leetcode】113—Path Sum II

2019-07-17  本文已影响0人  Gaoyt__
一、题目描述

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

相关题目: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
上一篇下一篇

猜你喜欢

热点阅读