UniqueBinarySearchTreesII   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 7
eloc 17
c 2
b 0
f 0
dl 0
loc 31
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A generateTrees() 0 7 2
A helper() 0 20 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
use leetcode\util\TreeNode;
8
9
class UniqueBinarySearchTreesII
10
{
11
    public static function generateTrees(int $n): array
12
    {
13
        if ($n <= 0) {
14
            return [];
15
        }
16
17
        return self::helper(1, $n);
18
    }
19
20
    private static function helper(int $start, int $end): array
21
    {
22
        $ans = [];
23
        if ($start > $end) {
24
            $ans[] = null;
25
        }
26
        for ($i = $start; $i <= $end; $i++) {
27
            $lefts = self::helper($start, $i - 1);
28
            $rights = self::helper($i + 1, $end);
29
            foreach ($lefts as $left) {
30
                foreach ($rights as $right) {
31
                    $root = new TreeNode($i);
32
                    $root->left = $left;
33
                    $root->right = $right;
34
                    $ans[] = $root;
35
                }
36
            }
37
        }
38
39
        return $ans;
40
    }
41
}
42