zoukankan      html  css  js  c++  java
  • LeetCode 95. 不同的二叉搜索树 II

    95. 不同的二叉搜索树 II

    Difficulty: 中等

    给定一个整数 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
    

    提示:

    • 0 <= n <= 8

    Solution

    Language: 全部题目

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def generateTrees(self, n: int) -> List[TreeNode]:
            if not n: return []
            
            def helper(start, end):
                if start > end: return [None,]
    ​
                res = []
                for i in range(start, end + 1): # start=end的时候该循环还可以进行一次,此时左子树和右子树都为None,根节点为i
                    lTree = helper(start, i-1)
                    rTree = helper(i+1, end)
                    for l in lTree:
                        for r in rTree:
                            node = TreeNode(i)
                            node.left = l
                            node.right = r
                            res.append(node)
                return res
    ​
            return helper(1,n)
    
  • 相关阅读:
    二分查找法
    Three-way Partition
    百面机器学习读书笔记
    天才在左,疯子在右
    Coach Shane's Daily English Dictaion 6-10
    Coach Shane's Daily English Dictation 1-5
    国外有意思的网站
    docker操作指南
    创建docker本地仓库的步骤
    tensorflow去掉warning的方法
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14032046.html
Copyright © 2011-2022 走看看