Given an integer 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
Subscribe to see which companies asked this question
该题比第一题难在要返回所有的BST树,第一题只需要返回BST树的个数
具体做法是:
1. 选出根结点后应该先分别求解该根的左右子树集合,也就是根的左子树有若干种,它们组成左子树集合,根的右子树有若干种,它们组成右子树集合。
2. 然后将左右子树相互配对,每一个左子树都与所有右子树匹配,每一个右子树都与所有的左子树匹配。然后将两个子树插在根结点上。
3. 最后,把根结点放入链表中。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<TreeNode> generateTrees(int n) { 12 if(n < 1) return new ArrayList<TreeNode>(); 13 return generate(1,n); 14 } 15 16 public List<TreeNode> generate(int left,int right){ 17 List<TreeNode> ans = new ArrayList<TreeNode>(); 18 if(left > right){ 19 ans.add(null); 20 return ans; 21 } 22 for(int i = left; i <= right; i++){ 23 List<TreeNode> leftlist = generate(left,i-1); 24 List<TreeNode> rightlist = generate(i+1,right); 25 for(TreeNode le : leftlist){ 26 for(TreeNode ri : rightlist){ 27 TreeNode node = new TreeNode(i); 28 node.left = le; 29 node.right = ri; 30 ans.add(node); 31 } 32 } 33 } 34 return ans; 35 } 36 }
第一题链接: