|
| 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 | + /** |
| 13 | + * @param TreeNode $root |
| 14 | + * @param Integer $sum |
| 15 | + * @return Boolean |
| 16 | + */ |
| 17 | + function hasPathSum($root, $sum) { |
| 18 | + $s=0; |
| 19 | + return self::hasPathSumUtil($root,$sum,$s); |
| 20 | + } |
| 21 | + |
| 22 | + function hasPathSumUtil($root, $sum, $s) |
| 23 | + { |
| 24 | + if($root == null) |
| 25 | + return false; |
| 26 | + if($root->left==null && $root->right==null) |
| 27 | + { |
| 28 | + $s = $s + $root->val; |
| 29 | + if ($s == $sum) |
| 30 | + return true; |
| 31 | + return false; |
| 32 | + } |
| 33 | + $s = $s + $root->val; |
| 34 | + $left = self::hasPathSumUtil($root->left, $sum, $s); |
| 35 | + $right = self::hasPathSumUtil($root->right, $sum, $s); |
| 36 | + |
| 37 | + if($left || $right) |
| 38 | + return true; |
| 39 | + |
| 40 | + return false; |
| 41 | + } |
| 42 | +} |
0 commit comments