-
Notifications
You must be signed in to change notification settings - Fork 0
/
0095_Unique_Binary_Search_Trees_II.java
46 lines (40 loc) · 1.62 KB
/
0095_Unique_Binary_Search_Trees_II.java
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
/*
* 95. Unique Binary Search Trees II
* Problem Link: https://leetcode.com/problems/unique-binary-search-trees-ii/
* Difficulty: Medium
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
public List<TreeNode> generateTrees(int n) {
// Calls the recursive helper function to generate subtrees from 1 to n
return generateSubtrees(1, n);
}
private List<TreeNode> generateSubtrees(int low, int high) {
// Initialize an empty result list
List<TreeNode> result = new ArrayList<>();
// If low is greater than high, the subtree is empty, so add null to the result list
if (low > high) {
result.add(null);
return result;
}
// Generate all possible subtrees by iterating from low to high
for (int i = low; i <= high; i++) {
// Recursively generate all possible left subtrees
List<TreeNode> leftList = generateSubtrees(low, i-1);
// Recursively generate all possible right subtrees
List<TreeNode> rightList = generateSubtrees(i+1, high);
// Merge the left, current, and right subtrees to create new trees
for (TreeNode left: leftList) {
for (TreeNode right: rightList) {
// Create a new tree with current node i and left and right subtrees
result.add(new TreeNode(i, left, right));
}
}
}
return result;
}
}