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

    题目:

    不同的二叉搜索树 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 
    

      

  • 相关阅读:
    Gym
    HDU
    HDU
    POJ
    洛谷P3690 Link Cut Tree (动态树)
    Gym
    P4294 [WC2008]游览计划 (斯坦纳树)
    洛谷P3264 [JLOI2015]管道连接 (斯坦纳树)
    HDU
    Controller调试接口
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12884256.html
Copyright © 2011-2022 走看看