【LeetCode】113. Path Sum II 解题报告(Python)
标签(空格分隔): LeetCode
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/
题目地址:https://leetcode.com/problems/path-sum-ii/description/
题目描述:
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
题目大意
在一棵二叉树中,找出从根节点到叶子节点的和为target的所有路径。
解题方法
其实一看这个题就能看出来这个是经典的回溯法的题目。看来是我手生了,竟然一下没写出来。
我卡在的地方在于回溯的时候root的处理方式,最后有下面两种处理方式吧。我更倾向于第二种,先把root给添加上去再回溯。
# 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]]
"""
res = []
self.dfs(root, sum, res, [])
return res
def dfs(self, root, target, res, path):
if not root: return
path += [root.val]
if sum(path) == target and not root.left and not root.right:
res.append(path[:])
return
if root.left:
self.dfs(root.left, target, res, path[:])
if root.right:
self.dfs(root.right, target, res, path[:])
path.pop(-1)
换了一种做法,貌似看起来更简单直白了。
# 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]]
"""
if not root: return []
res = []
self.dfs(root, sum, res, [root.val])
return res
def dfs(self, root, target, res, path):
if not root: return
if sum(path) == target and not root.left and not root.right:
res.append(path)
return
if root.left:
self.dfs(root.left, target, res, path + [root.left.val])
if root.right:
self.dfs(root.right, target, res, path + [root.right.val])
日期
2018 年 6 月 22 日 ———— 这周的糟心事终于完了