-
Notifications
You must be signed in to change notification settings - Fork 115
/
095-UniqueBinarySearchTree2.cs
48 lines (40 loc) · 1.36 KB
/
095-UniqueBinarySearchTree2.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//-----------------------------------------------------------------------------
// Runtime: 208ms
// Memory Usage: 28.8 MB
// Link: https://leetcode.com/submissions/detail/357928874/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _095_UniqueBinarySearchTree2
{
public IList<TreeNode> GenerateTrees(int n)
{
if (n == 0) return new List<TreeNode>();
return GenerateTrees(1, n);
}
public IList<TreeNode> GenerateTrees(int start, int end)
{
List<TreeNode> trees = new List<TreeNode>();
if (start > end)
{
trees.Add(null);
return trees;
}
for (int i = start; i <= end; i++)
{
var leftTrees = GenerateTrees(start, i - 1);
var rightTrees = GenerateTrees(i + 1, end);
foreach (var leftTree in leftTrees)
foreach (var rightTree in rightTrees)
{
var current = new TreeNode(i);
current.left = leftTree;
current.right = rightTree;
trees.Add(current);
}
}
return trees;
}
}
}