leetcode刷题笔记(Golang)--113. Path Sum II

113. 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.

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]
]

func pathSum(root *TreeNode, sum int) [][]int {
	res := [][]int{}
	dfs(root, sum, []int{}, &res)
	return res
}

func dfs(src *TreeNode, target int, path []int, paths *[][]int) {
	if src == nil {
		return
	}
	if src.Val == target && src.Left == nil && src.Right == nil {
		tmp := make([]int, len(path)+1)
		copy(tmp, append(path, src.Val))
		*paths = append(*paths, tmp)
	}
	dfs(src.Left, target-src.Val, append(path, src.Val), paths)
	dfs(src.Right, target-src.Val, append(path, src.Val), paths)
}
发布了98 篇原创文章 · 获赞 0 · 访问量 1473

猜你喜欢

转载自blog.csdn.net/weixin_44555304/article/details/104385847