📑 题目:113. 路径总和 II

🚀 本题 LeetCode 传送门

题目大意

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。说明: 叶子节点是指没有子节点的节点。

解题思路

  • 这一题是第 257 题和第 112 题的组合增强版

代码

  1. package leetcode
  2. /**
  3. * Definition for a binary tree node.
  4. * type TreeNode struct {
  5. * Val int
  6. * Left *TreeNode
  7. * Right *TreeNode
  8. * }
  9. */
  10. // 解法一
  11. func pathSum(root *TreeNode, sum int) [][]int {
  12. var slice [][]int
  13. slice = findPath(root, sum, slice, []int(nil))
  14. return slice
  15. }
  16. func findPath(n *TreeNode, sum int, slice [][]int, stack []int) [][]int {
  17. if n == nil {
  18. return slice
  19. }
  20. sum -= n.Val
  21. stack = append(stack, n.Val)
  22. if sum == 0 && n.Left == nil && n.Right == nil {
  23. slice = append(slice, append([]int{}, stack...))
  24. stack = stack[:len(stack)-1]
  25. }
  26. slice = findPath(n.Left, sum, slice, stack)
  27. slice = findPath(n.Right, sum, slice, stack)
  28. return slice
  29. }
  30. // 解法二
  31. func pathSum1(root *TreeNode, sum int) [][]int {
  32. if root == nil {
  33. return [][]int{}
  34. }
  35. if root.Left == nil && root.Right == nil {
  36. if sum == root.Val {
  37. return [][]int{[]int{root.Val}}
  38. }
  39. }
  40. path, res := []int{}, [][]int{}
  41. tmpLeft := pathSum(root.Left, sum-root.Val)
  42. path = append(path, root.Val)
  43. if len(tmpLeft) > 0 {
  44. for i := 0; i < len(tmpLeft); i++ {
  45. tmpLeft[i] = append(path, tmpLeft[i]...)
  46. }
  47. res = append(res, tmpLeft...)
  48. }
  49. path = []int{}
  50. tmpRight := pathSum(root.Right, sum-root.Val)
  51. path = append(path, root.Val)
  52. if len(tmpRight) > 0 {
  53. for i := 0; i < len(tmpRight); i++ {
  54. tmpRight[i] = append(path, tmpRight[i]...)
  55. }
  56. res = append(res, tmpRight...)
  57. }
  58. return res
  59. }