您的位置:首页 > 编程语言 > Python开发

[leetcode] @python 113. Path Sum II

2016-03-13 17:02 681 查看

题目链接

https://leetcode.com/problems/path-sum-ii/

题目原文

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

For example:

Given the below binary tree and sum = 22,



return



题目大意

上一题的扩展版,返回满足所有符合条件的路径

解题思路

使用dfs遍历

代码

# 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, cursum, valuelist):
if root.left == None and root.right == None:
if cursum == sum:
ans.append(valuelist)
if root.left:
dfs(root.left, cursum + root.left.val, valuelist + [root.left.val])
if root.right:
dfs(root.right, cursum + root.right.val, valuelist + [root.right.val])

ans = []
if root == None:
return []
dfs(root, root.val, [root.val])
return ans
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: