leetcode — unique-binary-search-trees-ii
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
/**
* https://leetcode.com/problems/unique-binary-search-trees-ii
*
*
* Given 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
*
*
* confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
*
* OJ's Binary Tree Serialization:
*
* The serialization of a binary tree follows a level order traversal, where '#' signifies
* a path terminator where no node exists below.
*
* Here's an example:
*
* 1
* / \
* 2 3
* /
* 4
* \
* 5
*
* The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
*/
public class UniqueBinarySearchTree2 {
/**
* 找出所有唯一的二叉搜索树
*
* @param n
* @return
*/
public List<List<Character>> generateTree (int n) {
List<TreeNode> list = recursion(1, n);
List<List<Character>> result = new ArrayList<List<Character>>();
for (int i = 0; i < list.size(); i++) {
List<Character> chs = new ArrayList<Character>();
binarySearchTreeToArray(list.get(i), chs);
result.add(chs);
}
return result;
}
/**
* 求出根节点分别为min-max任意一个数的时候的所有二叉搜索树
* 当根节点为i,根节点已知的情况下,一棵二叉搜索树可能的情况等于左子树可能个数乘以右子树可能个数
* 先递归求出左右子树的个数,然后根据所有左右子树的情况构造出左右的根节点,这些根节点就是最后所有可能的二叉搜索树的根节点
*
* 递归结束的条件min>max
*
* @param min
* @param max
* @return
*/
public List<TreeNode> recursion (int min, int max) {
List<TreeNode> list = new ArrayList<TreeNode>();
if (min > max) {
list.add(null);
return list;
}
for (int i = min; i <= max; i++) {
List<TreeNode> leftNodes = recursion(min, i-1);
List<TreeNode> rightNodes = recursion(i+1, max);
for (int j = 0; j < leftNodes.size(); j++) {
for (int k = 0; k < rightNodes.size(); k++) {
TreeNode root = new TreeNode(i);
root.leftChild = leftNodes.get(j);
root.rightChild = rightNodes.get(k);
list.add(root);
}
}
}
return list;
}
/**
* 使用广度优先遍历将数转化为数组
*
* @param root
* @param chs
*/
public void binarySearchTreeToArray (TreeNode root, List<Character> chs) {
if (root == null) {
chs.add('#');
return;
}
List<TreeNode> list = new ArrayList<TreeNode>();
int head = 0;
int tail = 0;
list.add(root);
chs.add((char) (root.value + '0'));
tail ++;
TreeNode temp = null;
while (head < tail) {
temp = list.get(head);
if (temp.leftChild != null) {
list.add(temp.leftChild);
chs.add((char) (temp.leftChild.value + '0'));
tail ++;
} else {
chs.add('#');
}
if (temp.rightChild != null) {
list.add(temp.rightChild);
chs.add((char)(temp.rightChild.value + '0'));
tail ++;
} else {
chs.add('#');
}
head ++;
}
//去除最后不必要的
for (int i = chs.size()-1; i > 0; i--) {
if (chs.get(i) != '#') {
break;
}
chs.remove(i);
}
}
private class TreeNode {
TreeNode leftChild;
TreeNode rightChild;
int value;
public TreeNode(int value) {
this.value = value;
}
public TreeNode() {
}
}
public static void print (List<List<Character>> lists) {
for (int i = 0; i < lists.size(); i++) {
System.out.println(Arrays.toString(lists.get(i).toArray(new Character[lists.get(i).size()])));
}
System.out.println();
}
public static void main(String[] args) {
UniqueBinarySearchTree2 uniqueBinarySearchTree2 = new UniqueBinarySearchTree2();
print(uniqueBinarySearchTree2.generateTree(0));
print(uniqueBinarySearchTree2.generateTree(1));
print(uniqueBinarySearchTree2.generateTree(2));
print(uniqueBinarySearchTree2.generateTree(3));
}
}
``
leetcode — unique-binary-search-trees-ii的更多相关文章
- LeetCode: Unique Binary Search Trees II 解题报告
Unique Binary Search Trees II Given n, generate all structurally unique BST's (binary search trees) ...
- [LeetCode] Unique Binary Search Trees II 独一无二的二叉搜索树之二
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For e ...
- LeetCode - Unique Binary Search Trees II
题目: Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. F ...
- LeetCode——Unique Binary Search Trees II
Question Given an integer n, generate all structurally unique BST's (binary search trees) that store ...
- [Leetcode] Unique binary search trees ii 唯一二叉搜索树
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For e ...
- [LeetCode] Unique Binary Search Trees II dfs 深度搜索
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For e ...
- [leetcode]Unique Binary Search Trees II @ Python
原题地址:https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ 题意:接上一题,这题要求返回的是所有符合条件的二叉查找树,而上 ...
- LeetCode:Unique Binary Search Trees I II
LeetCode:Unique Binary Search Trees Given n, how many structurally unique BST's (binary search trees ...
- [LeetCode] 95. Unique Binary Search Trees II(给定一个数字n,返回所有二叉搜索树) ☆☆☆
Unique Binary Search Trees II leetcode java [LeetCode]Unique Binary Search Trees II 异构二叉查找树II Unique ...
- 【LeetCode】95. Unique Binary Search Trees II 解题报告(Python)
[LeetCode]95. Unique Binary Search Trees II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzh ...
随机推荐
- 单调栈&单调队列入门
单调队列是什么呢?可以直接从问题开始来展开. Poj 2823 给定一个数列,从左至右输出每个长度为m的数列段内的最小数和最大数. 数列长度:\(N <=10^6 ,m<=N\) 解法① ...
- js 原生转json 可以v8中运行
// load("D:/jsontest.js"); function test1(vvv) { print(vvv); } //把json str 转 json obj func ...
- 机器学习——KNN算法(k近邻算法)
一 KNN算法 1. KNN算法简介 KNN(K-Nearest Neighbor)工作原理:存在一个样本数据集合,也称为训练样本集,并且样本集中每个数据都存在标签,即我们知道样本集中每一数据与所属分 ...
- 理解pytorch中的softmax中的dim参数
import torch import torch.nn.functional as F x1= torch.Tensor( [ [1,2,3,4],[1,3,4,5],[3,4,5,6]]) y11 ...
- C++ struct结构体定义构造函数和析构函数,构造函数参数从VS2017平台转换到Qt5平台下构建出错,采用字符集转换函数将string类型转换为wstring,构建仍然出错!
调试win硬件驱动,需要利用VS编译的win驱动构建自己的Qt5GUI程序: 其中部分win驱动源码如下 device_file::device_file(const std::string& ...
- python--ModuleFoundError
python 模块导入错误: 1. 首先py文件名不能和导入的模块名相同 (我在学习matplotlib库的时候就把文件名设置成matplotlib 多次运行不成功) 2. 由于我电脑上只有numpy ...
- Django+wechatpy接入微信公众平台以及授权登录
确定Django环境可以正常运行,环境搭建见:Linux 搭建Nginx+uwsgi+Django环境 安装 wechatpy[cryptography] sudo pip3 install wech ...
- 34 文件地理数据库(GDB)变文件夹了怎么办
我们都知道文件地理数据库(GDB)是ArcGIS软件特有的格式,有其独特的设计之处,在文件资源管理器中显示为.gdb的文件夹,但是里面的文件却看不明白,而且将gdb文件夹在Windows资源管理器中直 ...
- mysql uodate 报错 You can't specify target table '**' for update in FROM clause
You can't specify target table 'sc' for update in FROM clause 背景:把“sc”表中“叶平”老师教的课的成绩都更改为此课程的平均成绩: 上面 ...
- Python tkinter 学习记录(一) --label 与 button
最简的形式 from tkinter import * root = Tk() # 创建一个Tk实例 root.wm_title("标题") # 修改标题 root.mainloo ...