[LeetCode] 95. Unique Binary Search Trees II

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

不同的二叉搜索树 II。

给你一个整数 n ,请你生成并返回所有由 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 题目总结

posted @ 2020-06-23 09:32  CNoodle  阅读(492)  评论(0编辑  收藏  举报