二叉搜索树构造篇
基于labuladong的算法网站,东哥带你刷二叉搜索树(构造篇)
1、不同的二叉搜索树
力扣第96题,不同的二叉搜索树
class Solution {
public int numTrees(int n) {
return count(1, n);
}
// 计算闭区间left到right组成BST的个数
int count(int left, int right) {
// base case
if (left > right) {
return 1;
}
int res = 0;
for (int root = left; root <= right; root++) {
// 找到该头节点左子树的能组成BST的个数
int leftCount = count(left, root - 1);
int rightCount = count(root + 1, right);
res += leftCount * rightCount;
}
return res;
}
}
上述解法会导致超出时间限制,因为重复计算太多,所以需要引入备忘录,如下:
[96]不同的二叉搜索树
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int numTrees(int n) {
// 采用备忘录
memo = new int[n + 1][n + 1];
return count(1, n);
}
int[][] memo;
// 计算闭区间left到right组成BST的个数
int count(int left, int right) {
// base case
if (left > right) {
return 1;
}
// 判断备忘录中是否存在
if (memo[left][right] != 0) {
return memo[left][right];
}
int res = 0;
for (int root = left; root <= right; root++) {
// 找到该头节点左子树的能组成BST的个数
int leftCount = count(left, root - 1);
int rightCount = count(root + 1, right);
res += leftCount * rightCount;
}
// 记录备忘录
memo[left][right] = res;
return res;
}
}
//leetcode submit region end(Prohibit modification and deletion)
2、不同的二叉搜索树Ⅱ
力扣第95题,不同的二叉搜索树Ⅱ
[95]不同的二叉搜索树 II
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<TreeNode> generateTrees(int n) {
return get(1, n);
}
// 在数组为left到right上生成所有BST的可能性的头节点,将头节点放入集合中并返回
List<TreeNode> get(int left, int right) {
LinkedList<TreeNode> res = new LinkedList<>();
// base case
if (left > right) {
res.add(null);
return res;
}
if (left == right) {
res.add(new TreeNode(left));
return res;
}
// 将头节点为数组中的每一个值进行遍历
for (int root = left; root <= right; root++) {
List<TreeNode> leftList = get(left, root - 1);
List<TreeNode> rightList = get(root + 1, right);
// 将每个可能性进行组合
for (TreeNode leftNode : leftList) {
for (TreeNode rightNode : rightList) {
TreeNode node = new TreeNode(root);
node.left = leftNode;
node.right = rightNode;
res.add(node);
}
}
}
return res;
}
}
//leetcode submit region end(Prohibit modification and deletion)