| Conditions | 10 |
| Paths | 8 |
| Total Lines | 26 |
| Code Lines | 17 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 11 | public static function averageOfLevels(TreeNode $root): array |
||
| 12 | { |
||
| 13 | if (!$root) { |
||
|
|
|||
| 14 | return []; |
||
| 15 | } |
||
| 16 | $ans = $queue = []; |
||
| 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 | } |
||
| 64 |