public ArrayList<TreeNode> generateTrees(int n) {
// Start typing your Java solution below
// DO NOT write main() function
return generateTrees(1, n);
}
public ArrayList<TreeNode> generateTrees(int start, int end) {
ArrayList<TreeNode> result = new ArrayList<TreeNode>();
if(start > end) {
result.add(null);
return result;
}
for(int i = start; i <= end; i++)
for(TreeNode left : generateTrees(start, i - 1))
for(TreeNode right : generateTrees(i + 1, end)) {
TreeNode root = new TreeNode(i);
root.left = left;
root.right = right;
result.add(root);
}
return result;
}
Unique Binary Search Trees II
最新推荐文章于 2022-01-13 04:43:51 发布