[LeetCode] 95. Unique Binary Search Trees II

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

Constraints:

  • 0 <= n <= 8

不同的二叉搜索树II。题意是给一个数字N,请输出所有能被从1到N组成的二叉搜索树。

我这里给出一个递归的思路,DP的思路我解释的不是很清楚。。。这道题跟版本一的思路差不多,处理好几个corner case之后,选取某一个节点当做根节点,然后比这个节点小的节点们递归去构成左子树,比这个节点大的节点们递归去构成右子树。

时间 - 求卡特兰数的复杂度

空间 - 求卡特兰数的复杂度

Java实现

 1 class Solution {
 2     public List<TreeNode> generateTrees(int n) {
 3         List<TreeNode> res = new ArrayList<TreeNode>();
 4         // corner case
 5         if (n == 0) {
 6             return res;
 7         }
 8         return helper(1, n);
 9     }
10 
11     private List<TreeNode> helper(int start, int end) {
12         List<TreeNode> res = new ArrayList<TreeNode>();
13         //此时没有数字,将 null 加入结果中
14         if (start > end) {
15             res.add(null);
16             return res;
17         }
18         //只有一个数字,当前数字作为一棵树加入结果中
19         if (start == end) {
20             TreeNode tree = new TreeNode(start);
21             res.add(tree);
22             return res;
23         }
24         //尝试每个数字作为根节点
25         for (int i = start; i <= end; i++) {
26             //得到所有可能的左子树
27             List<TreeNode> leftTrees = helper(start, i - 1);
28             //得到所有可能的右子树
29             List<TreeNode> rightTrees = helper(i + 1, end);
30             //左子树右子树两两组合
31             for (TreeNode leftTree : leftTrees) {
32                 for (TreeNode rightTree : rightTrees) {
33                     TreeNode root = new TreeNode(i);
34                     root.left = leftTree;
35                     root.right = rightTree;
36                     //加入到最终结果中
37                     res.add(root);
38                 }
39             }
40         }
41         return res;
42     }
43 }

LeetCode 题目总结

猜你喜欢

转载自www.cnblogs.com/cnoodle/p/13180385.html