[leetcode tree]95. Unique Binary Search Trees II

时间:2023-03-09 05:54:56
[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组成的所有可能的树
 class Solution(object):
def generateTrees(self, n):
def node(v,l,r):
n = TreeNode(v)
n.left = l
n.right = r
return n
def tree(first,last):
return [node(v,l,r) for v in range(first,last+1)
for l in tree(first,v-1)
for r in tree(v+1,last)] or [None]
return tree(1,n) if n else []