题意:
解题思路:
思路:
1. 递归,从根节点出发,每经过一个叶节点,用sum减去该叶节点值,直到走到叶节点;
2. 如果走到叶节点,sum差值为0,则说明找到了从根节点到叶节点的数之和等于sum值;
3. 递归返回即可;
PHP代码实现:
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($value) { $this->val = $value; }
* }
*/
class Solution {
/**
* @param TreeNode $root
* @param Integer $sum
* @return Boolean
*/
function hasPathSum($root, $sum) {
if ($root == null) return false;
if ($root->left == null && $root->right == null) {
return $sum - $root->val == 0;
}
return $this->hasPathSum($root->left, $sum - $root->val) ||
$this->hasPathSum($root->right, $sum - $root->val);
}
}
GO代码实现:
func hasPathSum(root *TreeNode, sum int) bool {
if root == nil {
return false
}
if root.Left == nil && root.Right == nil {
return sum == root.Val
}
return hasPathSum(root.Left, sum - root.Val) || hasPathSum(root.Right, sum - root.Val)
}