Created
September 9, 2013 05:42
-
-
Save charlespunk/6491892 to your computer and use it in GitHub Desktop.
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
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. | |
For example, | |
Given n = 3, your program should return all 5 unique BST's shown below. | |
1 3 3 2 1 | |
\ / / / \ \ | |
3 2 1 1 3 2 | |
/ / \ \ | |
2 1 2 3 |
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
/** | |
* Definition for binary tree | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; left = null; right = null; } | |
* } | |
*/ | |
public class Solution { | |
public ArrayList<TreeNode> generateTrees(int n) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
return generateTrees(1, n); | |
} | |
private ArrayList<TreeNode> generateTrees(int begin, int end){ | |
ArrayList<TreeNode> result = new ArrayList<TreeNode>(); | |
if(begin > end) result.add(null); | |
else{ | |
for(int i = begin; i <= end; i++){ | |
ArrayList<TreeNode> left = generateTrees(begin, i - 1); | |
ArrayList<TreeNode> right = generateTrees(i + 1, end); | |
for(int j = 0; j < left.size(); j++){ | |
for(int k = 0; k < right.size(); k++){ | |
TreeNode node = new TreeNode(i); | |
node.left = left.get(j); | |
node.right = right.get(k); | |
result.add(node); | |
} | |
} | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment