/
112.path-sum.php
69 lines (58 loc) · 1.33 KB
/
112.path-sum.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
namespace LeetCode\PathSum;
/*
* @lc app=leetcode id=112 lang=php
*
* [112] Path Sum
*/
// @lc code=start
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution
{
/**
* @param TreeNode $root
* @param int $targetSum
* @return Boolean
*/
public function hasPathSum($root, $targetSum)
{
$total = 0;
$total = $total + $root->val;
if (is_null($root->val)) {
return false;
}
if (
$total == $targetSum &&
is_null($root->right) &&
is_null($root->left)
) {
return true;
}
if (!is_null($root->left)) {
$leftTotal = $this->hasPathSum($root->left, $targetSum - $total);
if ($leftTotal) {
return true;
}
}
if (!is_null($root->right)) {
$rightTotal = $this->hasPathSum($root->right, $targetSum - $total);
if ($rightTotal) {
return true;
}
}
return false;
}
}
// @lc code=end