LeetCode(中等)_95不同的二叉搜索树 II

95. 不同的二叉搜索树 II(中等)

题目

给你一个整数 n ,请你生成并返回所有由 n 个节点组成
且节点值从 1 到 n 互不相同的不同 二叉搜索树 。可以按 任意顺序 返回答案。

请添加图片描述

思路+代码

搜索二叉树:结点>左子树的数,结点<右子树的数

递归
for i  in  range(1,n+1):
	依次求左,右子树的搜索二叉树
	需要递归,不断的求搜索二叉树,直到为None
#Python
class Solution:
    def generateTrees(self, n: int) -> List[TreeNode]:
        def smallTrees(head, end):
            if head > end:
                return [None,]
            Trees = []
            for i in range(head, end + 1): 
                leftTrees = smallTrees(head, i - 1)
                rightTrees = smallTrees(i + 1, end)
                for l in leftTrees:
                    for r in rightTrees:
                        newTree = TreeNode(i)
                        newTree.left = l
                        newTree.right = r
                        Trees.append(newTree)
            return Trees
        return smallTrees(1, n) if n else []
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值