题意:

image.png

解题思路:

  1. 思路:O(n2)(这题跟112基本一样,不同点在于把所有符合条件的路径记录下来)
  2. 1. 递归,从根节点出发,每经过一个叶节点,用sum减去该叶节点值,直到走到叶节点;
  3. 2. 如果走到叶节点,sum差值为0,则说明找到了从根节点到叶节点的数之和等于sum值;
  4. 3. 递归返回即可;

PHP代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * class TreeNode {
  4. * public $val = null;
  5. * public $left = null;
  6. * public $right = null;
  7. * function __construct($value) { $this->val = $value; }
  8. * }
  9. */
  10. class Solution {
  11. /**
  12. * @param TreeNode $root
  13. * @param Integer $sum
  14. * @return Integer[][]
  15. */
  16. public $res = [];
  17. function pathSum($root, $sum) {
  18. if ($root == null) return $this->res;
  19. $this->helper($root, [], $sum);
  20. return $this->res;
  21. }
  22. function helper($root, $array, $sum) {
  23. if ($root == null) return;
  24. array_push($array, $root->val);
  25. if ($root->left == null && $root->right == null) {
  26. if ($sum - $root->val == 0) {
  27. array_push($this->res, $array);
  28. }
  29. return;
  30. }
  31. $this->helper($root->left, $array, $sum - $root->val);
  32. $this->helper($root->right, $array, $sum - $root->val);
  33. }
  34. }

GO代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. var res [][]int
  10. func pathSum(root *TreeNode, sum int) [][]int {
  11. res = [][]int{}
  12. helper(root, []int{}, sum)
  13. return res
  14. }
  15. func helper(root *TreeNode, array []int, sum int) {
  16. if root == nil {
  17. return
  18. }
  19. array = append(array, root.Val)
  20. if root.Left == nil && root.Right == nil {
  21. if sum == root.Val {
  22. r := make([]int, len(array))
  23. copy(r, array)
  24. res = append(res, r)
  25. }
  26. }
  27. helper(root.Left, array, sum - root.Val)
  28. helper(root.Right, array, sum - root.Val)
  29. }