[leetcode tree]95. 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



输入n,求出所有1-n组成的所有可能的树


 1 class Solution(object):
 2     def generateTrees(self, n):
 3         def node(v,l,r):
 4             n = TreeNode(v)
 5             n.left = l
 6             n.right = r
 7             return n
 8         def tree(first,last):
 9             return [node(v,l,r) for v in range(first,last+1)
10                                 for l in tree(first,v-1)
11                                 for r in tree(v+1,last)] or [None]
12         return tree(1,n) if n else []
原文地址:https://www.cnblogs.com/fcyworld/p/6519609.html