|
| 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 Integer[][] |
| 16 | + */ |
| 17 | + function pathSum($root, $sum) { |
| 18 | + $res = []; |
| 19 | + $temp = []; |
| 20 | + |
| 21 | + $curSum = 0; |
| 22 | + self::pathSumUtil($root, $sum, $curSum, $res,$temp); |
| 23 | + |
| 24 | + return $res; |
| 25 | + } |
| 26 | + |
| 27 | + function pathSumUtil($root, $sum, $curSum, &$res, &$temp) |
| 28 | + { |
| 29 | + |
| 30 | + if($root==null) |
| 31 | + return; |
| 32 | + array_push($temp, $root->val); |
| 33 | + if($root->left==null && $root->right==null) |
| 34 | + { |
| 35 | + $curSum = $curSum + $root->val; |
| 36 | + |
| 37 | + if($sum==$curSum) |
| 38 | + { |
| 39 | + array_push($res, $temp); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + $curSum = $curSum + $root->val; |
| 44 | + self::pathSumUtil($root->left, $sum, $curSum, $res, $temp); |
| 45 | + self::pathSumUtil($root->right, $sum, $curSum, $res, $temp); |
| 46 | + array_pop($temp); |
| 47 | + } |
| 48 | +} |
0 commit comments