题意:

image.png

解题思路:

  1. 思路:
  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 Boolean
  15. */
  16. function hasPathSum($root, $sum) {
  17. if ($root == null) return false;
  18. if ($root->left == null && $root->right == null) {
  19. return $sum - $root->val == 0;
  20. }
  21. return $this->hasPathSum($root->left, $sum - $root->val) ||
  22. $this->hasPathSum($root->right, $sum - $root->val);
  23. }
  24. }

GO代码实现:

  1. func hasPathSum(root *TreeNode, sum int) bool {
  2. if root == nil {
  3. return false
  4. }
  5. if root.Left == nil && root.Right == nil {
  6. return sum == root.Val
  7. }
  8. return hasPathSum(root.Left, sum - root.Val) || hasPathSum(root.Right, sum - root.Val)
  9. }