LeetCode - Unique Binary Search Trees II
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For 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
Solution:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; left = null; right = null; } 8 * } 9 */ 10 public class Solution { 11 public ArrayList<TreeNode> generateTree(int start, int end){ 12 ArrayList<TreeNode> result = new ArrayList<TreeNode>(); 13 if(start > end){ 14 result.add(null); 15 return result; 16 } 17 ArrayList<TreeNode> leftTree = new ArrayList<TreeNode>(); 18 ArrayList<TreeNode> rightTree = new ArrayList<TreeNode>(); 19 for(int i = start; i <= end; i++){ 20 leftTree = generateTree(start, i - 1); 21 rightTree = generateTree(i + 1, end); 22 for(int j = 0; j < leftTree.size(); j++){ 23 for(int k = 0; k < rightTree.size(); k++){ 24 TreeNode n = new TreeNode(i + 1); 25 n.left = leftTree.get(j); 26 n.right = rightTree.get(k); 27 result.add(n); 28 } 29 } 30 } 31 return result; 32 } 33 public ArrayList<TreeNode> generateTrees(int n) { 34 // Start typing your Java solution below 35 // DO NOT write main() function 36 return generateTree(0, n-1); 37 } 38 }