Unique Binary Search Trees
Problem
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
Note
DP
Solution
public class Solution { public int numTrees(int n) { int[] count = new int[n+1]; count[0] = 1; for (int i = 1; i <= n; i++) { for (int root = 1; root <= i; root++) { int left = count[root-1]; int right = count[i-root]; count[i] += left*right; } } return count[n]; }}
Unique Binary Search Trees II
Problem
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
Note
DFS
Solution
class Solution { public ListgenerateTrees(int n) { if (n == 0) return new ArrayList<>(); return helper(1, n); } private List helper(int start, int end) { List res = new ArrayList<>(); if (start > end) { res.add(null); return res; } for (int i = start; i <= end; i++) { List left = helper(start, i-1); List right = helper(i+1, end); for (TreeNode leftNode: left) { for (TreeNode rightNode: right) { TreeNode root = new TreeNode(i); root.left = leftNode; root.right = rightNode; res.add(root); } } } return res; }}