Unique Binary Search Trees I & II
Given n, how many structurally unique BSTs (binary search trees) that store values 1...n?
Example
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 public int numTrees(int n) { 3 int[] result = new int[n + 1]; 4 result[0] = result[1] = 1; 5 6 for (int i = 2; i <= n; ++i) { 7 for (int j = 0; j < i; ++j) { // j refers to the number of nodes in the left subtree 8 result[i] += result[j] * result[i - j - 1]; 9 } 10 } 11 return result[n]; 12 } 13 }
Unique Binary Search Trees II
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
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
分析:
这题是要求把每一个树都找出来。从上一题我们知道,当root选取i时,它的左子树是节点从1到i -1的数组成的,右子树是i + 1到n的数组成的。那么我们创建一个函数,返回从 start 到end这两个值之间所有树的root.
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<>(); 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 }

浙公网安备 33010602011771号