https://leetcode.com/problems/unique-binary-search-trees-ii/
給定一個(gè)正整數(shù),求出1~n的所有正整數(shù)能組成的BST組合
public List<TreeNode> generateTrees2(int n) {
List<TreeNode> res = new ArrayList<TreeNode>();
if (n == 0) {
return res;
}
res = generateTrees2Helper(1, n);
return res;
}
public List<TreeNode> generateTrees2Helper(int left, int right) {
List<TreeNode> res = new ArrayList<TreeNode>();
if (left > right) {
res.add(null);
return res;
}
for (int i = left; i <= right; i++) {
List<TreeNode> leftList = generateTrees2Helper(left, i - 1);
List<TreeNode> rightList = generateTrees2Helper(i + 1, right);
for (int j = 0; j < leftList.size(); j++) {
for (int k = 0; k < rightList.size(); k++) {
TreeNode root = new TreeNode(i);
root.left = leftList.get(j);
root.right = rightList.get(k);
res.add(root);
}
}
}
return res;
}