public class C3 { public static void main(String[] args) {
ArrayList<TreeNode> res = generateTrees(5);
System.out.println(res);
} public static ArrayList<TreeNode> generateTrees(int n) {
if(n == 0){
return new ArrayList<TreeNode>();
}
return generateTrees(1, n);//从1作为root开始,到n作为root结束
} private static ArrayList<TreeNode> generateTrees(int left, int right){
ArrayList<TreeNode> res = new ArrayList<TreeNode>();
if (left > right){
res.add(null);
return res;
}
for (int i = left; i <= right; i++){
ArrayList<TreeNode> lefts = generateTrees(left, i-1); //以i作为根节点,左子树由[1,i-1]构成
ArrayList<TreeNode> rights = generateTrees(i+1, right); //右子树由[i+1, n]构成
for (int j = 0; j < lefts.size(); j++){
for (int k = 0; k < rights.size(); k++){
TreeNode root = new TreeNode(i);
root.left = lefts.get(j);
root.right = rights.get(k);
res.add(root);//存储所有可能行
}
}
}
return res;
} public static class TreeNode {
TreeNode left;
TreeNode right;
int val;
public TreeNode () {}
public TreeNode (int val) {
this.val = val;
}
}
}