imajinyun /
leetcode-php
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace leetcode; |
||
| 6 | |||
| 7 | use leetcode\util\TreeNode; |
||
| 8 | |||
| 9 | class FindLargestValueInEachTreeRow |
||
| 10 | { |
||
| 11 | public static function largestValues(?TreeNode $tree): array |
||
| 12 | { |
||
| 13 | if (!$tree) { |
||
| 14 | return []; |
||
| 15 | } |
||
| 16 | |||
| 17 | $ans = $queue = []; |
||
|
0 ignored issues
–
show
Unused Code
introduced
by
Loading history...
|
|||
| 18 | $queue = [$tree]; |
||
| 19 | while ($queue) { |
||
|
0 ignored issues
–
show
The expression
$queue of type array<integer,leetcode\util\TreeNode> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.
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 Loading history...
|
|||
| 20 | [$curr, $n] = [[], count($queue)]; |
||
| 21 | for ($i = 0; $i < $n; $i++) { |
||
| 22 | $node = array_shift($queue); |
||
| 23 | if ($node instanceof TreeNode) { |
||
| 24 | array_push($curr, $node->val); |
||
| 25 | if ($node->left) { |
||
| 26 | array_push($queue, $node->left); |
||
| 27 | } |
||
| 28 | if ($node->right) { |
||
| 29 | array_push($queue, $node->right); |
||
| 30 | } |
||
| 31 | } |
||
| 32 | } |
||
| 33 | if ($curr) { |
||
|
0 ignored issues
–
show
The expression
$curr of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.
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 Loading history...
|
|||
| 34 | array_push($ans, max($curr)); |
||
| 35 | } |
||
| 36 | } |
||
| 37 | |||
| 38 | return $ans; |
||
| 39 | } |
||
| 40 | |||
| 41 | public static function largestValues2(?TreeNode $tree): array |
||
| 42 | { |
||
| 43 | if (!$tree) { |
||
| 44 | return []; |
||
| 45 | } |
||
| 46 | $ans = []; |
||
| 47 | self::dfs($tree, 0, $ans); |
||
| 48 | |||
| 49 | return $ans; |
||
| 50 | } |
||
| 51 | |||
| 52 | private static function dfs(?TreeNode $node, int $depth, array & $ans): void |
||
| 53 | { |
||
| 54 | if ($node instanceof TreeNode) { |
||
| 55 | if ($depth === count($ans)) { |
||
| 56 | array_push($ans, $node->val); |
||
| 57 | } else { |
||
| 58 | $ans[$depth] = max($ans[$depth], $node->val); |
||
| 59 | } |
||
| 60 | self::dfs($node->left, $depth + 1, $ans); |
||
| 61 | self::dfs($node->right, $depth + 1, $ans); |
||
| 62 | } |
||
| 63 | } |
||
| 64 | } |
||
| 65 |