UniqueBinarySearchTreesII::generateTrees()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 3
c 2
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 1
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