[Leetcode Series] [algorithm] [medium] different binary search tree II (Cattleya number of issues))

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 C_{n + 1}the first number cattleya term n + 1, then:

C_{n + 1} = C_{0}C_{n} + C_{1}C_{n - 1} + ... + C_{n}C_{0} = \sum _{i = 0}^{n}C_{i}C_{n - i} = \frac {2(2n + 1)}{n + 2}C_{n}\approx \frac {4^{n}}{n^{\frac {2}{3}}\sqrt{\pi }}

among them,C_{0} = 1, C_{1} = 1

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:

  1. Select a number, as the current node value
  2. Use less than the current value of the digital recursive call themselves, create the left subtree
  3. Use larger than the current value of the digital recursive call themselves, create the right subtree
  4. 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)

 

Published 100 original articles · won praise 4 · Views 1462

Guess you like

Origin blog.csdn.net/songyuwen0808/article/details/105394152