BinaryTreeLevelOrderTraversal   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 14
eloc 30
c 2
b 0
f 0
dl 0
loc 54
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A helper() 0 15 5
A levelOrder2() 0 9 3
A levelOrder() 0 24 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\TreeNode;
8
9
class BinaryTreeLevelOrderTraversal
10
{
11
    public static function levelOrder(TreeNode $root): array
12
    {
13
        $ans = $queue = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $queue is dead and can be removed.
Loading history...
14
        if (empty($root)) {
15
            return $ans;
16
        }
17
        $queue = [$root];
18
        while ($queue) {
0 ignored issues
show
Bug Best Practice introduced by
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 empty(..) or ! empty(...) instead.

Loading history...
19
            $curr = [];
20
            for ($i = 0, $n = count($queue); $i < $n; $i++) {
21
                /** @var \leetcode\util\TreeNode $node */
22
                $node = array_shift($queue);
23
                $curr[] = $node->val;
24
                if ($node->left !== null) {
25
                    $queue[] = $node->left;
26
                }
27
                if ($node->right !== null) {
28
                    $queue[] = $node->right;
29
                }
30
            }
31
            $ans[] = $curr;
32
        }
33
34
        return $ans;
35
    }
36
37
    public static function levelOrder2(TreeNode $root): array
38
    {
39
        $ans = [];
40
        if (empty($root) || $root === null) {
41
            return $ans;
42
        }
43
        self::helper($ans, $root, 0);
44
45
        return $ans;
46
    }
47
48
    private static function helper(array &$ans, TreeNode $node, int $curr): void
49
    {
50
        if ($node === null) {
51
            return;
52
        }
53
        if (count($ans) < $curr + 1) {
54
            $ans[] = [];
55
        }
56
        $ans[$curr][] = $node->val;
57
58
        if ($node->left) {
59
            self::helper($ans, $node->left, $curr + 1);
60
        }
61
        if ($node->right) {
62
            self::helper($ans, $node->right, $curr + 1);
63
        }
64
    }
65
}
66