Unique Binary Search Trees I
Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?
Example:
Input: 3
Output: 5
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0 for i in range(n+1)]
dp[0] = 1
dp[1] = 1
for i in range(2, n+1):
for j in range(1, i+1):
dp[i] += dp[j-1] * dp[i-j]
return dp[n]
** Unique Binary Search Trees II**
Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.
Example:
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Every number in range(1,n) can be a root.
For every root, we can build left trees and right trees by choosing new roots for them.
class Solution:
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
def generate(start,end):
if(start>end):
return [None,]
alltree=[]
for i in range(start,end+1):
lefttrees=generate(start,i-1)
righttrees=generate(i+1,end)
for l in lefttrees:
for r in righttrees:
cur=TreeNode(i)
cur.left=l
cur.right=r
alltree.append(cur)
return alltree
return generate(1,n) if n else []