/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/funcpathSum(root*TreeNode,targetSumint)[][]int{varpath[]intvarans[][]intvardfsfunc(root*TreeNode,curSumint)dfs=func(root*TreeNode,curSumint){ifnil==root{ifcurSum==targetSum{ans=append(ans,append([]int(nil),path...))}return}path=append(path,root.Val)dfs(root.Left,curSum+root.Val)dfs(root.Right,curSum+root.Val)path=path[:len(path)-1]}dfs(root,0)returnans}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/funcpathSum(root*TreeNode,targetSumint)[][]int{varans[][]intvarpath[]intvardfsfunc(root*TreeNode,curSumint)dfs=func(root*TreeNode,curSumint){ifnil==root{return}curSum+=root.Valpath=append(path,root.Val)deferfunc(){path=path[:len(path)-1]}()ifroot.Left==nil&&root.Right==nil{ifcurSum==targetSum{ans=append(ans,append([]int(nil),path...))}return}dfs(root.Left,curSum)dfs(root.Right,curSum)}dfs(root,0)returnans}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/funcpathSum(root*TreeNode,targetSumint)[][]int{varans[][]intifnil==root{returnans}parent:=make(map[*TreeNode]*TreeNode)varbuildPathfunc(node*TreeNode)[]intbuildPath=func(node*TreeNode)[]int{varpath[]intfornode!=nil{path=append(path,node.Val)node=parent[node]}fori:=0;i<len(path)/2;i++{path[i],path[len(path)-1-i]=path[len(path)-1-i],path[i]}returnpath}parent[root]=niltypeelemstruct{node*TreeNodesumint}varqueue[]elemqueue=append(queue,elem{node:root,sum:root.Val})forlen(queue)>0{cur:=queue[0]queue=queue[1:]ifcur.node.Left==nil&&cur.node.Right==nil{ifcur.sum==targetSum{ans=append(ans,buildPath(cur.node))}}ifcur.node.Left!=nil{queue=append(queue,elem{node:cur.node.Left,sum:cur.sum+cur.node.Left.Val})parent[cur.node.Left]=cur.node}ifcur.node.Right!=nil{queue=append(queue,elem{node:cur.node.Right,sum:cur.sum+cur.node.Right.Val})parent[cur.node.Right]=cur.node}}returnans}