95. Unique Binary Search Trees II

problem description

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 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

algorithm thought

对于一个二叉树来说,最好使用递归解决问题。这里返回值是一系列的二叉树。对于一个range,我们可以首先定好一个中间节点当做二叉树的根节点,然后比这个值小的当做左子树,大的当右子树。这里我们就可以将代码简化很多了。但是单就这样做还是不行,会有大量的重复计算,比如1-10生成BST。首先利用5当中间节点的时候,1-4要当左子树,然后用6当中间节点的时候,还是会碰到1-4当左子树的情况。我们可以用动态规划的方法来避免重复计算。

code

algorithm analysis

这里是一种递归方法,时间复杂度还不会分析。使用动态规划解决之后时间还是不会太慢的

Last updated