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