unique-binary-search-trees II

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

这题是要让求出所有结构,而不是求有多少种结构。

还是一样,每个元素都可以作为根节点,当i作为根节点的时候,左边元素又可以生成多种结构的左子树的集合,右边元素可以生成多种结构的右子树的集合,然后将这些左右子树相互匹配,加到i的根节点中,就形成一颗树加入到list中。

1. 选出根结点后应该先分别求解该根的左右子树集合,也就是根的左子树有若干种,它们组成左子树集合,根的右子树有若干种,它们组成右子树集合。 
2. 然后将左右子树相互配对,每一个左子树都与所有右子树匹配,每一个右子树都与所有的左子树匹配。然后将两个子树插在根结点上。 
3. 最后,把根结点放入链表中。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public List<TreeNode> generateTrees(int n) {
        
        if(n<1) return new ArrayList<TreeNode>();
        
        return helper(1,n);
    }
    public List<TreeNode> helper(int start,int end){
        List<TreeNode> list=new ArrayList<>();
        
        if(end<start) {
            list.add(null);
            return list;
        }
        for(int i=start;i<=end;i++){
            //将i为根节点的所有左子树和右子树得到
            List<TreeNode> leftChild=helper(start,i-1);
            List<TreeNode> rightChild=helper(i+1,end);
            //遍历i作为根节点的所有左子树和右子树,依次匹配,作为i的左右子树。
            for(TreeNode left:leftChild){
                for(TreeNode right:rightChild){
                    TreeNode root=new TreeNode(i);
                    root.left=left;
                    root.right=right;
                    list.add(root);
                }
            }
        }
        
        return list;
    }
}
原文地址:https://www.cnblogs.com/xiaolovewei/p/8243462.html