InsertIntoABinarySearchTree::insertIntoBST()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 14
rs 9.6111
cc 5
nc 6
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\TreeNode;
8
9
class InsertIntoABinarySearchTree
10
{
11
    public static function insertIntoBST(?TreeNode $root, int $val): TreeNode
12
    {
13
        if (!$root) {
14
            return $val ? new TreeNode($val) : new TreeNode();
15
        }
16
17
        if ($root->val > $val) {
18
            $root->left = self::insertIntoBST($root->left, $val);
19
        }
20
        if ($root->val < $val) {
21
            $root->right = self::insertIntoBST($root->right, $val);
22
        }
23
24
        return $root;
25
    }
26
27
    public static function insertIntoBST2(?TreeNode $root, int $val): TreeNode
28
    {
29
        $curr = $root;
30
        while ($curr instanceof TreeNode) {
31
            if ($curr->val < $val) {
32
                if (!$curr->right) {
33
                    $curr->right = new TreeNode($val);
34
                    return $root;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $root could return the type null which is incompatible with the type-hinted return leetcode\util\TreeNode. Consider adding an additional type-check to rule them out.
Loading history...
35
                } else {
36
                    $curr = $curr->right;
37
                }
38
            }
39
            if ($curr->val > $val) {
40
                if (!$curr->left) {
41
                    $curr->left = new TreeNode($val);
42
                    return $root;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $root could return the type null which is incompatible with the type-hinted return leetcode\util\TreeNode. Consider adding an additional type-check to rule them out.
Loading history...
43
                } else {
44
                    $curr = $curr->left;
45
                }
46
            }
47
        }
48
49
        return new TreeNode($val);
50
    }
51
}
52