LeetCode 113. Path Sum II-求解路径之和等于目标值得所有路径

112 阅读1分钟

同样是转化为子问题,但是过程中带着中间结果

 * @description: 113. Path Sum II
	Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum.

	A leaf is a node with no children.
 * @return: 所有路径节点之和等于目标值
 * @author: kami
 * @关键词:妙啊
 * @date: 2021/7/6 7:55
*/
func pathSum(root *TreeNode, sum int) [][]int {
	var slice [][]int
	slice = findPath(root, sum, slice, []int(nil))
	return slice
}

func findPath(n *TreeNode, sum int, slice [][]int, stack []int) [][]int {
	if n == nil {
		return slice
	}
	sum -= n.Val
	stack = append(stack, n.Val)

	if sum == 0 && n.Left == nil && n.Right == nil {
		slice = append(slice, append([]int(nil), stack...))
		stack = stack[:len(stack)-1]
	}

	slice = findPath(n.Left, sum, slice, stack)
	slice = findPath(n.Right, sum, slice, stack)
	return slice
}