[Leetcode] Unique Binary Search Trees II
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
Solution:
算法上还是用求解NP问题的方法来求解,也就是N-Queens中介绍的在循环中调用递归函数求解子问题。思路是每次一次选取一个结点为根,然后递归求解左右子树的所有结果,最后根据左右子树的返回的所有子树,依次选取然后接上(每个左边的子树跟所有右边的子树匹配,而每个右边的子树也要跟所有的左边子树匹配,总共有左右子树数量的乘积种情况),构造好之后作为当前树的结果返回。
这道题的解题依据依然是:
当数组为 1,2,3,4,.. i,.. n时,基于以下原则的BST建树具有唯一性: 以i为根节点的树,其左子树由[1, i-1]构成, 其右子树由[i+1, n]构成。
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; left = null; right = null; } 8 * } 9 */ 10 public class Solution { 11 public List<TreeNode> generateTrees(int n) { 12 return myGenerateTrees(1,n); 13 } 14 15 private List<TreeNode> myGenerateTrees(int left, int right) { 16 // TODO Auto-generated method stub 17 List<TreeNode> al = new ArrayList<TreeNode>(); 18 if (left > right) { 19 al.add(null); 20 return al; 21 } 22 for(int i=left;i<=right;++i){ 23 List<TreeNode> lefts=myGenerateTrees(left, i-1); 24 List<TreeNode> rights=myGenerateTrees(i+1, right); 25 for(int j=0;j<lefts.size();++j){ 26 for(int k=0;k<rights.size();++k){ 27 TreeNode root=new TreeNode(i); 28 root.left=lefts.get(j); 29 root.right=rights.get(k); 30 al.add(root); 31 } 32 } 33 } 34 return al; 35 } 36 }