Given n, how many structurally unique BSTs (binary search trees) that store values 1...n?
Given n = 3, there are a total of 5 unique BST‘s.
1 3 3 2 1
\ / / / \ 3 2 1 1 3 2
/ / \ 2 1 2 3
当数组为 1,2,3,4,.. i,.. n时,基于以下原则的BST建树具有唯一性:以i为根节点的树,其左子树由[0, i-1]构成, 其右子树由[i+1, n]构成。那么,左子树由[0 , i -1]组成时,又有多少组合方式呢?这就可以递归了嘛。
1 public class Solution { 2 /** 3 * @paramn n: An integer 4 * @return: An integer 5 * 6 */ 7 public int numTrees(int n) { 8 if (n == 0 || n == 1) return 1; 9 10 int[] count = new int[n + 1]; 11 12 count[0] = 1; // no node 13 count[1] = 1; // one node 14 15 for (int i = 2; i <= n; i++) { 16 for (int j = 0; j < i; j++) { // 以j为root 17 count[i] += count[j] * count[i - j - 1]; 18 } 19 } 20 return count[n]; 21 } 22 }
Given n, generate all structurally unique BST‘s (binary search trees) that store values 1...n.
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
1 /** 2 * Definition of TreeNode: 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left, right; 6 * public TreeNode(int val) { 7 * this.val = val; 8 * this.left = this.right = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @paramn n: An integer 15 * @return: A list of root 16 */ 17 public ArrayList<TreeNode> generateTrees(int n) { 18 return generate(1, n); 19 } 20 21 private ArrayList<TreeNode> generate(int start, int end){ 22 ArrayList<TreeNode> treeList = new ArrayList<TreeNode>(); 23 24 if(start > end){ 25 treeList.add(null); 26 return treeList; 27 } 28 29 for(int i = start; i <= end; i++){ 30 ArrayList<TreeNode> left = generate(start, i-1); 31 ArrayList<TreeNode> right = generate(i+1, end); 32 for(TreeNode l: left){ 33 for(TreeNode r: right){ 34 TreeNode root = new TreeNode(i); 35 root.left = l; 36 root.right = r; 37 treeList.add(root); 38 } 39 } 40 } 41 return treeList; 42 } 43 }
Unique Binary Search Trees I & II
原文:http://www.cnblogs.com/beiyeqingteng/p/5654836.html