Total Complexity | 15 |
Total Lines | 51 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
9 | class BinaryTreeRightSideView |
||
10 | { |
||
11 | public static function rightSideView(?TreeNode $root): array |
||
12 | { |
||
13 | if (!$root) { |
||
14 | return []; |
||
15 | } |
||
16 | $ans = $queue = []; |
||
|
|||
17 | $queue = [$root]; |
||
18 | while ($queue) { |
||
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 |
||
60 | } |
||
61 | } |
||
62 | } |
||
63 |