Last active
August 23, 2017 22:07
-
-
Save cixuuz/50b2b496c413d01111ba719e66159bdb to your computer and use it in GitHub Desktop.
[95. Unique Binary Search Trees II] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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