Test Failed
Push — master ( f04b39...21ac5d )
by Jinyun
02:25
created

MaximumDepthOfBinaryTree::maxDepth2()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 21
rs 9.2222
cc 6
nc 7
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\TreeNode;
8
9
class MaximumDepthOfBinaryTree
10
{
11
    public static function maxDepth(TreeNode $root = null): int
12
    {
13
        if ($root === null) {
14
            return 0;
15
        }
16
        if ($root->left === null) {
17
            return self::maxDepth($root->right) + 1;
18
        }
19
        if ($root->right === null) {
20
            return self::maxDepth($root->left) + 1;
21
        }
22
23
        return max(self::maxDepth($root->left), self::maxDepth($root->right)) + 1;
24
    }
25
26
    public static function maxDepth2(?TreeNode $root): int
27
    {
28
        if (!$root) {
29
            return 0;
30
        }
31
        [$cnt, $queue] = [0, [$root]];
32
        while ($queue) {
33
            $size = count($queue);
34
            while ($size-- > 0) {
35
                $node = array_pop($queue);
36
                if ($node->left) {
37
                    array_push($queue, $node->left);
38
                }
39
                if ($node->right) {
40
                    array_push($queue, $node->right);
41
                }
42
            }
43
            $cnt++;
44
        }
45
46
        return $cnt;
47
    }
48
}
49