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

二、代码实现
# 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
网友评论