imajinyun /
leetcode-php
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace leetcode; |
||
| 6 | |||
| 7 | use leetcode\util\TreeNode; |
||
| 8 | |||
| 9 | class BinaryTreeRightSideView |
||
| 10 | { |
||
| 11 | public static function rightSideView(?TreeNode $root): array |
||
| 12 | { |
||
| 13 | if (!$root) { |
||
| 14 | return []; |
||
| 15 | } |
||
| 16 | $ans = $queue = []; |
||
|
0 ignored issues
–
show
Unused Code
introduced
by
Loading history...
|
|||
| 17 | $queue = [$root]; |
||
| 18 | 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...
|
|||
| 19 | $n = count($queue); |
||
| 20 | for ($i = 0; $i < $n; $i++) { |
||
| 21 | /** @var \leetcode\util\TreeNode $node */ |
||
| 22 | $node = array_shift($queue); |
||
| 23 | if ($node instanceof TreeNode) { |
||
| 24 | if ($i === $n - 1 && $node->val) { |
||
| 25 | array_push($ans, $node->val); |
||
| 26 | } |
||
| 27 | if ($node->left) { |
||
| 28 | array_push($queue, $node->left); |
||
| 29 | } |
||
| 30 | if ($node->right) { |
||
| 31 | array_push($queue, $node->right); |
||
| 32 | } |
||
| 33 | } |
||
| 34 | } |
||
| 35 | } |
||
| 36 | |||
| 37 | return $ans; |
||
| 38 | } |
||
| 39 | |||
| 40 | public static function rightSideView2(?TreeNode $root): array |
||
| 41 | { |
||
| 42 | if (!$root) { |
||
| 43 | return []; |
||
| 44 | } |
||
| 45 | $ans = []; |
||
| 46 | self::dfs($root, 0, $ans); |
||
| 47 | |||
| 48 | return $ans; |
||
| 49 | } |
||
| 50 | |||
| 51 | private static function dfs(?TreeNode $node, int $depth, array & $ans): void |
||
| 52 | { |
||
| 53 | if ($node instanceof TreeNode && $node->val) { |
||
| 54 | if ($depth + 1 > count($ans)) { |
||
| 55 | array_push($ans, 0); |
||
| 56 | } |
||
| 57 | $ans[$depth] = $node->val; |
||
| 58 | self::dfs($node->left, $depth + 1, $ans); |
||
| 59 | self::dfs($node->right, $depth + 1, $ans); |
||
| 60 | } |
||
| 61 | } |
||
| 62 | } |
||
| 63 |