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

是第96题的延伸,要求出所有可能性。

刚开始写了一个回溯法,但是由于没有办法在TreeNode中重写equals,导致需要重写的东西很多(主要这样做的话,一个一个添加TreeNode。会出现重复的情况),也就导致了时间很长。一百多ms。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List list = new ArrayList<TreeNode>();
public List<TreeNode> generateTrees(int n) { if( n == 0)
return list;
int[] pos = new int[n];
for( int i = 0;i<n;i++){
pos[i] = 1;
TreeNode root = new TreeNode(i+1);
getResult(root,pos);
pos[i] = 0;
}
return list;
} public void getResult(TreeNode root,int[] pos){ int flag = 0;
for( int i = 0;i<pos.length;i++){
if( pos[i] == 0){
addNode(root,i);
pos[i] = 1;
getResult(root,pos);
delNote(root,i);
pos[i] = 0;
flag = 1;
}
}
if( flag == 0){
TreeNode ans = getAns(root);
if( !isExist(ans) )
list.add(ans);
} }
public boolean isExist(TreeNode ans){
int size = list.size();
for( int i = 0;i<size;i++){
if( isSame((TreeNode)list.get(i),ans) )
return true;
}
return false; }
public boolean isSame(TreeNode node1,TreeNode node2){
if( node1.val != node2.val)
return false;
if( node1.left != null && node2.left != null){
if( !isSame(node1.left,node2.left) )
return false;
}else if( node1.left == null && node2.left == null)
;
else
return false;
if( node1.right != null && node2.right != null){
if( !isSame(node1.right,node2.right) )
return false;
}else if( node1.right == null && node2.right == null )
;
else
return false;
return true;
} public TreeNode getAns(TreeNode root){ TreeNode ans = new TreeNode(root.val);
if( root.left != null )
ans.left = getAns(root.left);
if( root.right != null)
ans.right = getAns(root.right);
return ans;
} public void addNode(TreeNode root,int i ){
while( true){
if( i+1 > root.val ){
if( root.right == null){
root.right = new TreeNode(i+1);
return ;
}else
root = root.right;
}else{
if( root.left == null){
root.left = new TreeNode(i+1);
return ;
}else
root = root.left;
}
}
}
public void delNote(TreeNode root,int i){
while( true){
if( i+1 > root.val ){
if( i+1 == root.right.val ){
root.right = null;
return ;
}else
root = root.right;
}else{
if( i+1 == root.left.val ){
root.left = null;
return ;
}else
root = root.left;
}
}
} }

然后看了网上的解答,有两个我认为还不错,一个是根据树的结构来回溯,效率很高,不会出现重复,

/**
* 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 ArrayList<TreeNode>();
} return gen(1, n);
} List<TreeNode> gen(int start, int end) {
ArrayList<TreeNode> heads = new ArrayList<TreeNode>();
if(start > end) {
heads.add(null);
return heads;
} for(int i = start; i <= end; i++) { List<TreeNode> lefts = gen(start, i - 1);
List<TreeNode> rights = gen(i + 1, end); for(TreeNode left : lefts) {
for(TreeNode right : rights) {
TreeNode head = new TreeNode(i);
head.left = left;
head.right = right;
heads.add(head);
}
}
} return heads; }
}

还有一种动态规划其实也就是第二种方法的改良。

public static List<TreeNode> generateTrees(int n) {
List<TreeNode>[] result = new List[n + 1];
result[0] = new ArrayList<TreeNode>();
if (n == 0) {
return result[0];
} result[0].add(null);
for (int len = 1; len <= n; len++) {
result[len] = new ArrayList<TreeNode>();
for (int j = 0; j < len; j++) {
for (TreeNode nodeL : result[j]) {
for (TreeNode nodeR : result[len - j - 1]) {
TreeNode node = new TreeNode(j + 1);
node.left = nodeL;
node.right = clone(nodeR, j + 1);
result[len].add(node);
}
}
}
}
return result[n];
} private static TreeNode clone(TreeNode n, int offset) {
if (n == null) {
return null;
}
TreeNode node = new TreeNode(n.val + offset);
node.left = clone(n.left, offset);
node.right = clone(n.right, offset);
return node;
}

leetcode 95 Unique Binary Search Trees II ----- java的更多相关文章

  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 独一无二的二叉搜索树之二

    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. ubuntu连接Android调试

    从这周开始尝试Android开发,记下点滴. 安装JDK.下载ADT不说,连接手机调试的时候出错,一堆问号??????????.网上一查,属于典型错误.试下来,有几步比较关键,容易忽视: 1.我机器上 ...

  2. Delphi日期时间 UNIX

    Delphi日期时间,就是常见的 2014-05-02 10:37:35 --------------------------------------------------------------- ...

  3. K2认证考试,为竞争力加分

    思科Cisco认证.ADOBE认证.微软认证.印度AIIT认证.华为认证.IBM认证等……在各种“证”满天飞的时候,如何独具慧眼选择最有含金量的证书? 八成 的人力资源主管会检查求职者的认证情况.(C ...

  4. DotNetBar v12.6.0.4 Fully Cracked

    更新信息: http://www.devcomponents.com/customeronly/releasenotes.asp?p=dnbwf&v=12.6.0.4 如果遇到破解问题可以与我 ...

  5. [Java]eclipse的使用

    1.android sdk help安装 使用SDK Manager.exe下载android sdk的时候把docs也勾选上. 在eclipse的android工程下的android.jar(在an ...

  6. CSS 的class属性居然可以并(有点像并,有点像与)操作

    <a href="javascript:;" class="btn btn-default doc-event-1">创建div容器</a&g ...

  7. Map的遍历

    @Test public void test() { Map<String,String> usersmap = new HashMap<>(); usersmap.put(& ...

  8. dotTracePerormance 工具

    今天凌晨 阿根廷对瑞士比赛已经过去,比分是1:0  阿根廷获胜:虽说我是伪球迷,但是也挺希望梅西进入决赛.昨晚也压了下90分之内  0:0  ,结果胜出:另一场压的是美国对比利时,也是压平,就这样二串 ...

  9. MongoDB 查询 (转) 仅限于C++开发

    1.find MongoDB使用find来进行查询.查询就是返回一个集合中文档的子集,子集合的范围从0个文档到整个集合.find的第一个参数 决定了要返回哪些文档.其形式也是一个文档,说明要查询的细节 ...

  10. EditText提示文字

    如图,在没有输入文字前,会显示提醒文字. 引用的是文本文件(strings.xml)中的对应文字 activity_main.xml对应的红色代码: <?xml version="1. ...