LeetCode 95. Unique Binary Search Trees II(独特的二进制搜索树 II)

原题

Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.

给定一个整数,生成所有结构上唯一的 BST (二进制搜索树) 存储值 1…n。

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

Note:

Follow up: Recursive solution is trivial, could you do it iteratively?

题目:
给定一个二叉树,返回其中序遍历(注意中序遍历的英写法:inorder traversal

Reference Answer

思路分析

这道题目的做法和之前的unique BST略有不同,但主体思想是一致的。选定一个点作为根,依次产生可行的子树,然后把解加到最后的解里面。

# 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):
        """
        :type n: int
        :rtype: List[TreeNode]
        """
        if n == 0:
            return []
        return self.getTrees(1, n)
        
    def getTrees(self, start, end):
        if start > end:
            return [None]
        solution = []
        for rootval in range(start, end+1):
            left = self.getTrees(start, rootval-1)
            right = self.getTrees(rootval+1, end)
            for i in left:
                for j in right:
                    root = TreeNode(rootval)
                    root.left = i
                    root.right = j
                    solution.append(root)
        return solution 
                

反思:

  1. 对于结果中的 [1,null,3,2] 中的 [null] 在代码中应该返回为 [None]

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/83032183