java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// 最后需要返回一个所有根节点的集合, 所以这个题思路有点怪
// 因为每次深搜返回左、右子树的根节点集合,所以还需要它动将他们拼接
public List<TreeNode> dfs(int left, int right){
List<TreeNode> allNodes = new ArrayList<>();
if(left > right){
allNodes.add(null);
return allNodes;
}
for(int i = left; i <= right; i++){
List<TreeNode> leftTrees = dfs(left, i - 1);
List<TreeNode> rightTrees = dfs(i + 1, right);
for(TreeNode leftNode : leftTrees){
for(TreeNode rightNode : rightTrees){
TreeNode now = new TreeNode(i);
now.left = leftNode;
now.right = rightNode;
allNodes.add(now);
}
}
}
return allNodes;
}
public List<TreeNode> generateTrees(int n) {
if(n == 0){
return new ArrayList<TreeNode>();
}
return dfs(1, n);
}
}