SameTree::isSameTree2()   B
last analyzed

Complexity

Conditions 7
Paths 5

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 19
rs 8.8333
cc 7
nc 5
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\TreeNode;
8
9
class SameTree
10
{
11
    public static function isSameTree(?TreeNode $p, ?TreeNode $q): bool
12
    {
13
        if ($p && $q) {
14
            return $p->val === $q->val &&
15
                self::isSameTree($p->left, $q->left) &&
16
                self::isSameTree($p->right, $q->right);
17
        }
18
19
        return $p === $q;
20
    }
21
22
    public static function isSameTree2(?TreeNode $p, ?TreeNode $q): bool
23
    {
24
        $stack = [[$p, $q]];
25
        while ($stack) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $stack of type array<integer,array<inte...de\util\TreeNode|null>> 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...
26
            [$m, $n] = array_pop($stack);
27
            if (!$m && !$n) {
28
                continue;
29
            }
30
            if (!$m || !$n) {
31
                return $m === $n;
32
            }
33
            if ($m->val !== $n->val) {
34
                return false;
35
            }
36
            array_push($stack, [$m->right, $n->right]);
37
            array_push($stack, [$m->left, $n->left]);
38
        }
39
40
        return true;
41
    }
42
}
43