(复习)[LeetCode]Unique Binary Search Trees II

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


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

For example,
Given n = 3, your program should return all 5 unique BST’s shown below.

1         3     3      2      1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

本题难度Medium。

【复杂度】
时间 O(N) 空间 O(N)

【思路】
根据数的范围​​​start,end​​​,选取某个数​​i​​​作为分割点,然后分别得到左子树和右子树的范围 ​​start,i-1​​​ ​​i+1, end​​​ ,然后分别求得两个子树的集合,然后进行组合从而得到树的集合​​trees​​。

【要点】
先求出两边子树的集合,再组合得到树的集合。

【注意】

1. 第20行​​​trees.add(null);​​​不能少,否则对于第28与29行来说,如果​​trees​​​里面什么都没有,是不能进行循环的!(null也是一个元素)
2. 如果输入​​​n=0​​,是要单独对待的(12-13行),系统要求此时结果里面什么都不能有,包括null!

【代码】

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<TreeNode> generateTrees(int n) {
if(n==0)
return new LinkedList<>();
return generate(1,n);
}
private List<TreeNode> generate(int start,int end){
List<TreeNode> trees=new LinkedList<>();
//base case
if(start>end){
trees.add(null);
return trees;
}

for(int i=start;i<=end;i++){
//get the Lists of left and right subTree respectively
List<TreeNode> leftSubs=generate(start,i-1);
List<TreeNode> rightSubs=generate(i+1,end);
for(TreeNode l:leftSubs)
for(TreeNode r:rightSubs){
TreeNode root=new TreeNode(i);
root.left=l;
root.right=r;
trees.add(root);
}
}
return trees;
}
}


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6