Enumerate binary trees UniqueBinaryTreesAll.java
public static List<BinaryTree<Integer>> generateAllBinaryTrees(int n) {return generateAllBinaryTreesHelper(1, n);
}
private static List<BinaryTree<Integer>> generateAllBinaryTreesHelper(
int start, int end) {
List<BinaryTree<Integer>> result = new ArrayList<>();
if (start > end) {
result.add(null);
return result;
}
for (int i = start; i <= end; ++i) {
// Tries all possible combinations of left subtrees and right subtrees.
List<BinaryTree<Integer>> leftresult = generateAllBinaryTreesHelper(start,
i - 1);
List<BinaryTree<Integer>> rightresult = generateAllBinaryTreesHelper(
i + 1, end);
for (BinaryTree<Integer> left : leftresult) {
for (BinaryTree<Integer> right : rightresult) {
result.add(new BinaryTree<>(i, left, right));
}
}
}
return result;
}