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. 面试题目-atof与ftoa

    /////////////////////////////////////////////////////////////////////////////// // // FileName : ato ...

  2. C# 轉義字符

    转义字符 意义 ASCII码值(十进制) \a 响铃(BEL) 007 \b 退格(BS) ,将当前位置移到前一列 008 \f 换页(FF),将当前位置移到下页开头 012 \n 换行(LF) ,将 ...

  3. io函数

    io函数一般分为两大类: 系统(不带缓存)调用: 如read.write.open 标准(带缓存)调用: fread.fwrite.fopen 上面说的带缓存/不带缓存是针对用户态的,内核态本身都是带 ...

  4. 图解傅里叶变换(so easy)

    话不多说先上两个GIF图. 第一个动画和第二个动画其实都是对时域的周期矩形形波(近似看成矩形波,并不是严格意义的矩形方波)进行傅里叶变换分析. 对于第一个图形来说,它侧重展示变换的本质之一:叠加性,每 ...

  5. Oracle top N实现

    在Oracle中实现select top N:由于Oracle不支持select top 语句,所以在Oracle中经常是用order by 跟rownum的组合来实现select top n的查询. ...

  6. vs2012 .netFramwork2.0发布到xp

    开发环境 windows server2008R2 VS2012  .net Framwork2.0 开发的winform程序 在有的xp系统下不能运行 选择 项目属性=>编译 Build=&g ...

  7. JS 基于面向对象的 轮播图1

    ---恢复内容开始--- 1 'use strict' 2 function Tab(id){ 3 if(!id)return; 4 this.oBox = document.getElementBy ...

  8. Ubuntu 14.10 下安装navicat

    1 下载navicat,网址http://www.navicat.com.cn/download,我下载的是navicat111_premium_cs.tar.gz 2 解压到合适的位置 3 进入解压 ...

  9. Note_Master-Detail Application(iOS template)_01_YJYAppDelegate.h

    //YJYAppDelegate.h #import <UIKit/UIKit.h> @interface YJYAppDelegate : UIResponder <UIAppli ...

  10. Java异常机制

    Java异常分类 异常表明程序运行发生了意外,导致正常流程发生错误,例如数学上的除0,打开一个文件但此文件实际不存在,用户输入非法的参数等.在C语言中我们处理这类事件一般是将其与代码正常的流程放在一起 ...