Test Failed
Push — master ( d2361c...f95e0f )
by Jinyun
02:08
created

zigzagLevelOrder()   B

Complexity

Conditions 11
Paths 22

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 34
rs 7.3166
cc 11
nc 22
nop 1

How to fix   Complexity   

Long Method

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:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\TreeNode;
8
9
class BinaryTreeZigzagLevelOrderTraversal
10
{
11
    public static function zigzagLevelOrder(TreeNode $root): array
12
    {
13
        if (empty($root)) {
14
            return [];
15
        }
16
        [$ans, $level, $queue] = [[], 1, []];
17
        $queue = [$root];
18
        while ($queue) {
19
            [$curr, $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 && $node->val) {
24
                    if ($level % 2 === 0 && $node->val) {
25
                        array_unshift($curr, $node->val);
26
                    } else {
27
                        array_push($curr, $node->val);
28
                    }
29
30
                    if ($node->left) {
31
                        array_push($queue, $node->left);
32
                    }
33
                    if ($node->right) {
34
                        array_push($queue, $node->right);
35
                    }
36
                }
37
            }
38
            if ($curr) {
0 ignored issues
show
Bug Best Practice introduced by
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 empty(..) or ! empty(...) instead.

Loading history...
39
                array_push($ans, $curr);
40
            }
41
            $level++;
42
        }
43
44
        return $ans;
45
    }
46
}
47