Test Failed
Push — master ( 21ac5d...b25d9d )
by Jinyun
02:24
created

SymmetricTree::isSymmetric()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 23
rs 8.4444
cc 8
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\TreeNode;
8
9
class SymmetricTree
10
{
11
    public static function isSymmetric(?TreeNode $root): bool
12
    {
13
        if (!$root) {
14
            return false;
15
        }
16
        $stack = [];
17
        array_push($stack, $root->left);
18
        array_push($stack, $root->right);
19
        while ($stack) {
20
            [$p, $q] = [array_shift($stack), array_shift($stack)];
21
            if (!$p && !$p) {
22
                continue;
23
            }
24
            if (!$p || !$q || $p->val !== $q->val) {
25
                return false;
26
            }
27
            array_push($stack, $p->left);
28
            array_push($stack, $q->right);
29
            array_push($stack, $p->right);
30
            array_push($stack, $q->left);
31
        }
32
33
        return true;
34
    }
35
36
    public static function isSymmetric2(?TreeNode $root): bool
37
    {
38
        if (!$root) {
39
            return false;
40
        }
41
42
        return self::helper($root->left, $root->right);
43
    }
44
45
    private static function helper(?TreeNode $p, ?TreeNode $q): bool
46
    {
47
        if (!$p && !$q) {
48
            return true;
49
        }
50
        if (!$p || !$q) {
51
            return false;
52
        }
53
54
        return $p->val === $q->val &&
55
            self::helper($p->left, $q->right) &&
56
            self::helper($p->right, $q->left);
57
    }
58
}
59