路径总和(Go)
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
func pathSum(root *TreeNode, sum int) [][]int { ret := [][]int{} path := []int{} dfs(&ret, root, path, sum) return ret } func dfs(ret *[][]int, root *TreeNode, path []int, target int) { switch { case root == nil: return case root.Left == nil && root.Right == nil && root.Val == target: dst := make([]int, len(path)+1) copy(dst, append(path, root.Val)) *ret = append(*ret, dst) return } path = append(path, root.Val) dfs(ret, root.Left, path, target-root.Val) dfs(ret, root.Right, path, target-root.Val) }