原题
https://leetcode.cn/problems/path-sum-ii/description/
思路
深度优先搜索
复杂度
时间:O(n)
空间:O(n)
Python代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
ans = []
def dfs(root, path):
if not root:
return
path.append(root.val)
if root.left is None and root.right is None and sum(path) == targetSum:
ans.append(path[:])
dfs(root.left, path)
dfs(root.right, path)
path.pop()
dfs(root, [])
return ans
Go代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum(root *TreeNode, targetSum int) [][]int {
var ans [][]int
var dfs func(*TreeNode, []int, int)
dfs = func(root *TreeNode, path []int, curSum int) {
if root == nil {
return
}
path = append(path, root.Val)
curSum += root.Val
if root.Left == nil && root.Right == nil && curSum == targetSum {
pathCopy := make([]int, len(path))
copy(pathCopy, path)
ans = append(ans, pathCopy)
}
dfs(root.Left, path, curSum)
dfs(root.Right, path, curSum)
path = path[:len(path)-1]
}
dfs(root, []int{}, 0)
return ans
}
253

被折叠的 条评论
为什么被折叠?



