156 - 95 不同的二叉搜索树2

题目

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

解答

不同的二叉树1是计算有多少个,现在是要把全部情况列出来。

递归

class Solution:
    def generateTrees(self, n: int) -> List[TreeNode]:
        def helper(start, end):
            if start > end:
                return [None, ]
            all_trees = []
            for i in range(start, end+1):
                left_trees = helper(start, i-1)
                right_trees = helper(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 helper(1, n) if n else []

Runtime: 52 ms, faster than 87.17% of Python3 online submissions for Unique Binary Search Trees II.

Memory Usage: 14.2 MB, less than 80.00% of Python3 online submissions for Unique Binary Search Trees II.

看不懂的解

https://leetcode.com/problems/unique-binary-search-trees-ii/discuss/31495/Should-be-6-Liner

Runtime: 60 ms, faster than 56.45% of Python3 online submissions for Unique Binary Search Trees II.

Memory Usage: 14.8 MB, less than 73.33% of Python3 online submissions for Unique Binary Search Trees II.

动态规划

https://leetcode.com/problems/unique-binary-search-trees-ii/discuss/31523/DP-solution-in-Python

Runtime: 44 ms, faster than 98.40% of Python3 online submissions for Unique Binary Search Trees II.

Memory Usage: 13.4 MB, less than 100.00% of Python3 online submissions for Unique Binary Search Trees II.

Last updated

Was this helpful?