Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active August 23, 2017 22:07
Show Gist options
  • Select an option

  • Save cixuuz/50b2b496c413d01111ba719e66159bdb to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/50b2b496c413d01111ba719e66159bdb to your computer and use it in GitHub Desktop.
[95. Unique Binary Search Trees II] #leetcode
class Solution {
// O(n^2) O(n^2)
public List<TreeNode> generateTrees(int n) {
if (n == 0) return new ArrayList<TreeNode>();
return genTree(1, n);
}
private List<TreeNode> genTree(int start, int end) {
List<TreeNode> list = new ArrayList<>();
if ( start > end ) {
list.add(null);
return list;
}
// this part can be ignored
if ( start == end ) {
list.add(new TreeNode(start));
return list;
}
List<TreeNode> left, right;
for (int i=start; i<=end; i++) {
left = genTree(start, i-1);
right = genTree(i+1, end);
for (TreeNode lnode : left) {
for (TreeNode rnode : right) {
TreeNode root = new TreeNode(i);
root.left = lnode;
root.right = rnode;
list.add(root);
}
}
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment