题目:
题解:
type pair struct {node *TreeNodeleft int
}func pathSum(root *TreeNode, targetSum int) (ans [][]int) {if root == nil {return}parent := map[*TreeNode]*TreeNode{}getPath := func(node *TreeNode) (path []int) {for ; node != nil; node = parent[node] {path = append(path, node.Val)}for i, j := 0, len(path)-1; i < j; i++ {path[i], path[j] = path[j], path[i]j--}return}queue := []pair{{root, targetSum}}for len(queue) > 0 {p := queue[0]queue = queue[1:]node := p.nodeleft := p.left - node.Valif node.Left == nil && node.Right == nil {if left == 0 {ans = append(ans, getPath(node))}} else {if node.Left != nil {parent[node.Left] = nodequeue = append(queue, pair{node.Left, left})}if node.Right != nil {parent[node.Right] = nodequeue = append(queue, pair{node.Right, left})}}}return
}