Path Sum II
原题链接
实现原理解析
该题使用深度搜索实现即可
python代码实现
import copy
# 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 __init__(self):
self.path = []
self.result = []
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
self.dfs(root, sum)
return self.result
def dfs(self, root, res):
if root is None:
return
elif root.left is None and root.right is None:
if sum(self.path) + root.val == res:
self.path.append(root.val)
path1 = copy.deepcopy(self.path)
self.result.append(path1)
self.path.pop()
else:
self.path.append(root.val)
self.pathSum(root.left, res)
self.pathSum(root.right, res)
self.path.pop()