码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode练习(Python):动态规划类:第95题:不同的二叉搜索树 II:给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。

时间:2020-05-13 20:10:25      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:pen   tco   二叉搜索树   iar   动态规划   大神   一个   tree node   efi   

题目:

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

思路:

遍历每一个节点,并且得到每个节点的左右子树,然后获得每个子树的样子就可以得出来了。

自己想了半天没法实现,参考了一下网上大神的程序,写的很好,很好理解。

程序:

# 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]:
        if n <= 0:
            return []
        def auxiliary(begin, end):
            auxiliary_result = []
            if begin > end:
                return [None]
            for index in range(begin, end + 1):
                left_part = auxiliary(begin, index - 1)
                right_part = auxiliary(index + 1, end)
                for left_node in left_part:
                    for right_node in right_part:
                        tree_node = TreeNode(index)
                        tree_node.left = left_node
                        auxiliary_result.append(tree_node)
                        tree_node.right = right_node
            return auxiliary_result
        result = auxiliary(1, n)
        return result 

  

Leetcode练习(Python):动态规划类:第95题:不同的二叉搜索树 II:给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。

标签:pen   tco   二叉搜索树   iar   动态规划   大神   一个   tree node   efi   

原文地址:https://www.cnblogs.com/zhuozige/p/12884256.html

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