码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 每日一题 95. 不同的二叉搜索树 II

时间:2020-06-21 15:46:28      阅读:40      评论:0      收藏:0      [点我收藏+]

标签:mamicode   int   efi   com   src   for   nbsp   bin   图片   

技术图片

递归

思路:

 

代码:

# 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]:
        def generate_trees(start, end):
            if start > end:
                return [None,]
            all_trees = []
            for i in range(start, end + 1):  
                left_trees = generate_trees(start, i - 1)
                right_trees = generate_trees(i + 1, end)
                for l in left_trees:
                    for r in right_trees:
                        current_tree = TreeNode(i)
                        current_tree.left = l
                        current_tree.right = r
                        all_trees.append(current_tree)
            
            return all_trees
        
        return generate_trees(1, n) if n else []

 

leetcode 每日一题 95. 不同的二叉搜索树 II

标签:mamicode   int   efi   com   src   for   nbsp   bin   图片   

原文地址:https://www.cnblogs.com/nilhxzcode/p/13172505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!