题目 96 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 Explanation: Given n = 3, there are a total of 5 unique BST's: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
Thinking
Selecting a number as the root node, the left and right sides subtree node number is also determined. * Number of kinds of the left subtree right subtree number = number of kinds of the root of the tree. As the root node through all numbers, to give the total number of trees.
def numTrees(self, n: int) -> int:
if n==0:
return 0
nums = collections.defaultdict(lambda:0)
nums[0] = 1
nums[1] = 1
for i in range(2,n+1):
if i % 2 == 1:
nums[i] = nums[(i-1)//2]**2
for j in range((i)//2):
nums[i] += 2*nums[j]*nums[i-1-j]
return nums[n]
题目 95 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] ] Explanation: The above output corresponds to the 5 unique BST's shown below: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
Thinking
Recursively, taking as a root node a number, this number is smaller than the number of all of the composition to the left of the tree, the composition of this number greater than the number to the right of the tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTree(self,nums):
if len(nums)==0:
return [None]
ans = []
for i in range(len(nums)):
l = self.generateTree(nums[:i])
r = self.generateTree(nums[i+1:])
for li in l:
for ri in r:
root = TreeNode(nums[i])
root.left = li
root.right = ri
ans.append(root)
return ans
def generateTrees(self, n: int) -> List[TreeNode]:
if n==0:
return None
nums = []
for i in range(1,n+1):
nums.append(i)
return self.generateTree(nums)