-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathProblem_8_Structurally_Unique_Binary_Search_Tree.java
More file actions
49 lines (40 loc) · 1.34 KB
/
Problem_8_Structurally_Unique_Binary_Search_Tree.java
File metadata and controls
49 lines (40 loc) · 1.34 KB
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
49
package Subsets;
// Problem Statement: Structurally Unique Binary Search Trees (hard)
// LeetCode Question: 95. Unique Binary Search Trees II
import java.util.ArrayList;
import java.util.List;
public class Problem_8_Structurally_Unique_Binary_Search_Tree {
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public List<TreeNode> findUniqueTrees(int n) {
if (n <= 0)
return new ArrayList<TreeNode>();
return findUniqueTreesRecursive(1, n);
}
public List<TreeNode> findUniqueTreesRecursive(int start, int end) {
List<TreeNode> result = new ArrayList<>();
if (start > end) {
result.add(null);
return result;
}
for (int i = start; i <= end; i++) {
List<TreeNode> leftSubtrees = findUniqueTreesRecursive(start, i - 1);
List<TreeNode> rightSubtrees = findUniqueTreesRecursive(i + 1, end);
for (TreeNode leftTree : leftSubtrees) {
for (TreeNode rightTree : rightSubtrees) {
TreeNode root = new TreeNode(i);
root.left = leftTree;
root.right = rightTree;
result.add(root);
}
}
}
return result;
}
}