Given an integer
n
, return all the structurally unique BST’s (binary search trees), which has exactly n
nodes of unique values from 1
to n
. Return the answer in any order.Example 1:
Input: n = 3
Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
*
1 <= n <= 8
题目大意:
给定n,求所有val为1-n的BST的所有可能性
解题思路:
DFS中比较难的catalan类型。
解题步骤:
N/A
注意事项:
- root = TreeNode(i)要在最内层for循环中
Python代码:
1 | def generateTrees(self, n: int) -> List[TreeNode]: |
算法分析:
时间复杂度Catalan数为O(C[n] += C[i-1]*C[n-i])
,空间复杂度O(1)