8.4 LeetCode 95, 96 Unique BST I & II
// 95 return all unique BST roots. public ArrayList<TreeNode> generateTrees(int n) { // 2nd ans // Start typing your Java solution below // DO NOT write main() function return generateTrees(1,n); } public ArrayList<TreeNode> generateTrees(int a, int b){ ArrayList<TreeNode> res = new ArrayList<TreeNode>(); if(a>b){ res.add(null); }else if(a==b){ res.add(new TreeNode(a)); }else if(a < b){ for(int i=a;i<=b;i++){ ArrayList<TreeNode> left = generateTrees(a,i-1); // left subtree ArrayList<TreeNode> right = generateTrees(i+1,b); // right subtree for(TreeNode l:left) for(TreeNode r:right){ TreeNode root = new TreeNode(i); root.left=l; root.right=r; res.add(root); } } } return res; }
// return number of Unique BST public int numTrees(int n) { int[] res = new int[n+1]; // notice it is n+1, for res[n] represents the num of unique BST of n nodes. res[0] = 1; // 0 node 1 structure res[1] = 1; // 1 node 1 structure for(int i = 2; i <= n; i++) { int sum = 0; for(int j = 1; j <= i; j++) { int left = i - j; int right = j - 1; sum += res[left] * res[right]; } res[i] = sum; } return res[n]; }