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.
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
confused what
Solution:
If it asks us to list all possibilities, use DFS in most cases.
DFS in the code is tricky.
"{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.Solution:
If it asks us to list all possibilities, use DFS in most cases.
DFS in the code is tricky.
* 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) {
return helper(1,n);
}
public ArrayList<treenode> helper(int begin, int end){
ArrayList<treenode> ret = new ArrayList<treenode>();
if(begin > end){
ret.add(null);
return ret;
}
for(int i = begin; i <= end; i++){ // for all roots
ArrayList<treenode> left = helper(begin, i-1); //generate left subtree
ArrayList<treenode> right = helper(i+1, end); //generate right subtree
for(TreeNode l : left){
for(TreeNode r : right){
TreeNode tmp = new TreeNode(i);
tmp.left = l;
tmp.right = r;
ret.add(tmp);
}
}
}
return ret;
}
}
No comments:
Post a Comment