ValidateBinarySearchTree   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 16
eloc 23
c 2
b 0
f 0
dl 0
loc 43
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isValidBST() 0 3 1
B helper() 0 14 7
B isValidBST2() 0 20 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\TreeNode;
8
9
class ValidateBinarySearchTree
10
{
11
    public static function isValidBST(TreeNode $root): bool
12
    {
13
        return self::helper($root);
14
    }
15
16
    public static function isValidBST2(TreeNode $root): bool
17
    {
18
        if ($root === null) {
19
            return true;
20
        }
21
        [$stack, $prev] = [[], null];
22
        while ($root !== null || $stack) {
23
            while ($root !== null) {
24
                $stack[] = $root;
25
                $root = $root->left;
26
            }
27
            $root = array_pop($stack);
28
            if ($prev !== null && $prev instanceof TreeNode && $root->val <= $prev->val) {
29
                return false;
30
            }
31
            $prev = $root;
32
            $root = $root->right;
33
        }
34
35
        return true;
36
    }
37
38
    private static function helper(TreeNode $root = null, $min = null, $max = null): bool
39
    {
40
        if ($root === null) {
41
            return true;
42
        }
43
        if ($min !== null && $min >= $root->val) {
44
            return false;
45
        }
46
        if ($max !== null && $max <= $root->val) {
47
            return false;
48
        }
49
50
        return self::helper($root->left, $min, $root->val) &&
51
            self::helper($root->right, $root->val, $max);
52
    }
53
}
54