topic:
Topic links: https://leetcode-cn.com/problems/unique-binary-search-trees-ii/
Problem-solving ideas:
If only the number required, directly by the number Cattleya recursion formulas Solution:
Suppose the first number cattleya term n + 1, then:
among them,
Other common examples conform Cattleya number recursion formulas are: parenthesized, the stack order, convex polygon triangulation, n-number of matching right parentheses
So if you do not list all the examples, just from zero recursion, you can find the number of any of Cattleya
But the need to list all the examples here, so I can not use this method, you need to use a recursive way through all possibilities
When the idea of recursion:
- Select a number, as the current node value
- Use less than the current value of the digital recursive call themselves, create the left subtree
- Use larger than the current value of the digital recursive call themselves, create the right subtree
- Move backward a value as the current node, continue to repeat the cycle
Code:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
def create_res(start, end):
# 如果start > end,说明以及到了叶子节点,直接返回None
if start > end:
return [None,]
res = []
for i in range(start, end + 1):
# 创建左子树
left_trees = create_res(start, i - 1)
# 创建右子树
right_trees = create_res(i + 1, end)
for left in left_trees:
for right in right_trees:
# 如果是叶子节点,left和right都为None
# 之后再向上递归,逐渐创建一系列完整的树
node = TreeNode(i)
node.left = left
node.right = right
res.append(node)
return res
if 0 == n:
return []
return create_res(1, n)