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)
}