Test Failed
Push — master ( 5e2519...18b97f )
by Jinyun
02:17
created

SearchInABinarySearchTree::searchBST()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 12
rs 10
cc 4
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\TreeNode;
8
9
class SearchInABinarySearchTree
10
{
11
    public static function searchBST(?TreeNode $root, int $val): ?TreeNode
12
    {
13
        if (!$root) {
14
            return $root;
15
        }
16
17
        if ($root->val > $val) {
18
            return self::searchBST($root->left, $val);
19
        } elseif ($root->val < $val) {
20
            return self::searchBST($root->right, $val);
21
        } else {
22
            return $root;
23
        }
24
    }
25
26
    public static function searchBST2(?TreeNode $root, int $val): ?TreeNode
27
    {
28
        if (!$root) {
29
            return $root;
30
        }
31
        $curr = $root;
32
        while ($curr && $curr instanceof TreeNode) {
33
            if ($curr->val > $val) {
34
                $curr = $curr->left;
35
            } elseif ($curr->val < $val) {
36
                $curr = $curr->right;
37
            } else {
38
                return $curr;
39
            }
40
        }
41
42
        return $curr;
43
    }
44
}
45