Skip to the content.

leetcode [95] 不同的二叉搜索树 II


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


给定一个整数 n,生成所有由 1 … n 为节点所组成的二叉搜索树。

示例:

输入: 3
输出:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
解释:
以上的输出对应以下 5 种不同结构的二叉搜索树:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
class Solution:
    def generateTreesCore(self, start, end) -> List[TreeNode]:
        if end == start:
            return [None]
        if end - start == 1:
            return [TreeNode(start)]
        res = []
        for i in range(start, end):
            left = self.generateTreesCore(start, i)
            right = self.generateTreesCore(i + 1, end)
            for le in left:
                for ri in right:
                    head = TreeNode(i)
                    head.left = le
                    head.right = ri
                    res.append(head)
        return res

    def generateTrees(self, n: int) -> List[TreeNode]:
        if n == 0:
            return []
        return self.generateTreesCore(1, n + 1)