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

这道题是之前的 Unique Binary Search Trees 的延伸,之前那个只要求算出所有不同的二叉搜索树的个数,这道题让把那些二叉树都建立出来。这种建树问题一般来说都是用递归来解,这道题也不例外,划分左右子树,递归构造。这个其实是用到了大名鼎鼎的分治法 Divide and Conquer,类似的题目还有之前的那道 Different Ways to Add Parentheses 用的方法一样,用递归来解,划分左右两个子数组,递归构造。刚开始时,将区间 [1, n] 当作一个整体,然后需要将其中的每个数字都当作根结点,其划分开了左右两个子区间,然后分别调用递归函数,会得到两个结点数组,接下来要做的就是从这两个数组中每次各取一个结点,当作当前根结点的左右子结点,然后将根结点加入结果 res 数组中即可,参见代码如下:

解法一:

class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
if (n == ) return {};
return helper(, n);
}
vector<TreeNode*> helper(int start, int end) {
if (start > end) return {nullptr};
vector<TreeNode*> res;
for (int i = start; i <= end; ++i) {
auto left = helper(start, i - ), right = helper(i + , end);
for (auto a : left) {
for (auto b : right) {
TreeNode *node = new TreeNode(i);
node->left = a;
node->right = b;
res.push_back(node);
}
}
}
return res;
}
};

我们可以使用记忆数组来优化,保存计算过的中间结果,从而避免重复计算。注意这道题的标签有一个是动态规划 Dynamic Programming,其实带记忆数组的递归形式就是 DP 的一种,memo[i][j] 表示在区间 [i, j] 范围内可以生成的所有 BST 的根结点,所以 memo 必须是一个三维数组,这样在递归函数中,就可以去 memo 中查找当前的区间是否已经计算过了,是的话,直接返回 memo 中的数组,否则就按之前的方法去计算,最后计算好了之后要更新 memo 数组,参见代码如下:

解法二:

class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
if (n == ) return {};
vector<vector<vector<TreeNode*>>> memo(n, vector<vector<TreeNode*>>(n));
return helper(, n, memo);
}
vector<TreeNode*> helper(int start, int end, vector<vector<vector<TreeNode*>>>& memo) {
if (start > end) return {nullptr};
if (!memo[start - ][end - ].empty()) return memo[start - ][end - ];
vector<TreeNode*> res;
for (int i = start; i <= end; ++i) {
auto left = helper(start, i - , memo), right = helper(i + , end, memo);
for (auto a : left) {
for (auto b : right) {
TreeNode *node = new TreeNode(i);
node->left = a;
node->right = b;
res.push_back(node);
}
}
}
return memo[start - ][end - ] = res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/95

类似题目:

Unique Binary Search Trees

Different Ways to Add Parentheses

参考资料:

https://leetcode.com/problems/unique-binary-search-trees-ii/

https://leetcode.com/problems/unique-binary-search-trees-ii/discuss/31494/A-simple-recursive-solution

https://leetcode.com/problems/unique-binary-search-trees-ii/discuss/31535/20ms-C%2B%2B-top-down-DP-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 95. Unique Binary Search Trees II 独一无二的二叉搜索树之二的更多相关文章

  1. [LeetCode] 95. Unique Binary Search Trees II(给定一个数字n,返回所有二叉搜索树) ☆☆☆

    Unique Binary Search Trees II leetcode java [LeetCode]Unique Binary Search Trees II 异构二叉查找树II Unique ...

  2. [leetcode]95. Unique Binary Search Trees II给定节点形成不同BST的集合

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

  3. [LeetCode] 95. Unique Binary Search Trees II 唯一二叉搜索树 II

    Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For e ...

  4. leetcode 95 Unique Binary Search Trees II ----- java

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

  5. leetCode 95.Unique Binary Search Trees II (唯一二叉搜索树) 解题思路和方法

    Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For e ...

  6. [leetcode]95 Unique Binary Search Trees II (Medium)

    原题 字母题添加链接描述 一开始完全没有思路.. 百度看了别人的思路,对于这种递归构造的题目还是不熟,得多做做了. 这个题目难在构造出来.一般构造树都需要递归. 从1–n中任意选择一个数当做根节点,所 ...

  7. LeetCode 95. Unique Binary Search Trees II 动态演示

    比如输入为n, 这道题目就是让返回由1,2,... n的组成的所有二叉排序树,每个树都必须包含这n个数 这是二叉树的排列组合的题目.排列组合经常用DFS来解决. 这道题比如输入为3,也就是求start ...

  8. 【LeetCode】95. Unique Binary Search Trees II 解题报告(Python)

    [LeetCode]95. Unique Binary Search Trees II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzh ...

  9. leetcode 96. Unique Binary Search Trees 、95. Unique Binary Search Trees II 、241. Different Ways to Add Parentheses

    96. Unique Binary Search Trees https://www.cnblogs.com/grandyang/p/4299608.html 3由dp[1]*dp[1].dp[0]* ...

随机推荐

  1. let/const特性

        let: 1.声明的变量不存在预解析: console.log(a); let a=1; 2.变量名不允许重复(在同一作用域下): { let a=1; let a=2; console.lo ...

  2. 为什么Linux 普通用户在虚拟机界面可以reboot 用ssh 不能reboot

    应该是有 类似的权限控制. 如果是 localhost , 那么普通用户允许重启. 如果不是localhost,  比如ssh远程的,必须验证root权限.

  3. spring的@ControllerAdvice注解

    @ControllerAdvice注解是Spring3.2中新增的注解,学名是Controller增强器,作用是给Controller控制器添加统一的操作或处理. 对于@ControllerAdvic ...

  4. FreeBSD Set a Default Route / Gateway

    Task: View / Display FreeBSD Routing Table Use netstat command with -r option:$ netstat -r$ netstat ...

  5. NLP第一课(我也是才开始学)

    闲着无聊的时候,我就会问问自己,编程也有了五年经验了,除了增删改查,我还会什么,有一天我跳槽,去面试的时候,我能比那些年轻而且期望薪资待遇低的年轻毕业生,我有什么优势,而且我只是一个专科的机电系学生, ...

  6. 古老的txt下传和txt上载

    1.下传文件 TYPES:BEGIN OF TY_DATA, A2 TYPE CHAR20, B2 TYPE I, C2 TYPE CHAR20, END OF TY_DATA. DATA:IT_DA ...

  7. 关于@HtmlHelper帮助器参数

    @Html.ActionLink("首页", "Index", "Index", new{},new { @class = "na ...

  8. Python - 模块 - 第十六天

    Python 模块 在前面的几个章节中我们脚本上是用 python 解释器来编程,如果你从 Python 解释器退出再进入,那么你定义的所有的方法和变量就都消失了. 为此 Python 提供了一个办法 ...

  9. SQL 除去数字中多于的0

    /* 除掉多于的0 */ CREATE FUNCTION [dbo].[fn_ClearZero] ( ) ) ) AS BEGIN ); IF (@inValue = '') SET @return ...

  10. ubuntu 18.04 修改Apache默认目录

    ubuntu 18.04 修改Apache默认目录 安装是直接运行 sudu apt install apache2 安装之后要修改目录 vi /etc/apache2/sites-available ...