1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace leetcode; |
6
|
|
|
|
7
|
|
|
use leetcode\util\TreeNode; |
8
|
|
|
|
9
|
|
|
class BinaryTreeMaximumPathSum |
10
|
|
|
{ |
11
|
|
|
public static function maxPathSum(TreeNode $root): int |
12
|
|
|
{ |
13
|
|
|
$max = PHP_INT_MIN; |
14
|
|
|
self::helper($root, $max); |
15
|
|
|
|
16
|
|
|
return $max; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
public static function maxPathSum2(TreeNode $root): int |
20
|
|
|
{ |
21
|
|
|
$helper = static function (TreeNode $node) { |
22
|
|
|
[$order, $stack] = [[], [$node]]; |
23
|
|
|
while ($stack) { |
|
|
|
|
24
|
|
|
$top = array_pop($stack); |
25
|
|
|
array_push($order, $top); |
26
|
|
|
if ($top->left) { |
27
|
|
|
array_push($stack, $top->left); |
28
|
|
|
} |
29
|
|
|
if ($top->right) { |
30
|
|
|
array_push($stack, $top->right); |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
return array_reverse($order); |
34
|
|
|
}; |
35
|
|
|
if (!$root->left && !$root->right) { |
36
|
|
|
return $root->val; |
37
|
|
|
} |
38
|
|
|
[$ans, $map] = [PHP_INT_MIN, []]; |
39
|
|
|
$nodes = $helper($root); |
40
|
|
|
foreach ($nodes as $node) { |
41
|
|
|
$left = $right = 0; |
42
|
|
|
if ($node->left) { |
43
|
|
|
$left = spl_object_hash($node->left); |
44
|
|
|
} |
45
|
|
|
if ($node->right) { |
46
|
|
|
$right = spl_object_hash($node->right); |
47
|
|
|
} |
48
|
|
|
$left = max(0, $map[$left] ?? 0); |
49
|
|
|
$right = max(0, $map[$right] ?? 0); |
50
|
|
|
$map[spl_object_hash($node)] = max($left, $right) + $node->val; |
51
|
|
|
$ans = max($ans, $left + $node->val + $right); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $ans; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
private static function helper(?TreeNode $node, int &$max): int |
58
|
|
|
{ |
59
|
|
|
if (! $node) { |
60
|
|
|
return 0; |
61
|
|
|
} |
62
|
|
|
$left = max(0, self::helper($node->left, $max)); |
63
|
|
|
$right = max(0, self::helper($node->right, $max)); |
64
|
|
|
$max = max($max, $left + $right + $node->val); |
65
|
|
|
|
66
|
|
|
return max($left, $right) + $node->val; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.