LeetCode OJ - Unique Binary Search Tree 1 && 2
第一道题是Catalan数,主需要求f(n),第二道题是用递归的方法,不断的组装这个棵树。
下面是两个AC代码:
1 /** 2 * Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 3 * Catalan number sequence 4 * @param n 5 * @return 6 */ 7 public int numTrees(int n){ 8 if(n<=1) 9 return 1; 10 int[] f = new int[n+1];// the catalan 11 f[0] = 1; 12 f[1] = 1; 13 int i=2; 14 while(i<=n){ 15 int j = 0; 16 while(j<=i-1){ 17 f[i] += f[j]*f[i-1-j]; 18 j++; 19 } 20 i++; 21 } 22 return f[n]; 23 } 24 /** 25 * Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. 26 * @param n 27 * @return 28 */ 29 public ArrayList<TreeNode> generateTrees(int n) { 30 31 if(n<=0) 32 { 33 ArrayList<TreeNode> r = new ArrayList<TreeNode>(); 34 r.add(null); 35 return r; 36 } 37 return genTrees(1,n); 38 } 39 /** 40 * 41 * @param start [ 42 * @param end ] 43 * @return 44 */ 45 private ArrayList<TreeNode> genTrees(int start, int end){ 46 if(start>end) 47 return null; 48 ArrayList<TreeNode> r = new ArrayList<TreeNode>(); 49 //only one element 50 if(start == end) 51 { 52 r.add(new TreeNode(start)); 53 return r; 54 } 55 int i = start; 56 while(i<=end){ 57 ArrayList<TreeNode> subL = genTrees(start,i-1); 58 ArrayList<TreeNode> subR = genTrees(i+1,end); 59 TreeNode root; 60 //connect the left & right subtree 61 if(subL!=null && subR!=null){ 62 for(TreeNode left: subL){ 63 for(TreeNode right:subR){ 64 root = new TreeNode(i); 65 root.left = left; 66 root.right = right; 67 r.add(root); 68 } 69 } 70 } 71 if(subL == null && subR !=null){ 72 for(TreeNode right: subR){ 73 root = new TreeNode(i); 74 root.right = right; 75 r.add(root); 76 } 77 } 78 if(subR == null && subL !=null){ 79 for(TreeNode left: subL){ 80 root = new TreeNode(i); 81 root.left = left; 82 r.add(root); 83 } 84 } 85 i++; 86 } 87 return r; 88 }
有问题可以和我联系,bettyting2010#163 dot com