算法15 之二叉树排序
2016-05-13 17:38
260 查看
顾名思义,二叉树排序就是利用二叉搜索树的特点进行排序,前面提到过二叉搜索树的特点是,左子节点比自己小,右子节点比自己大,那么二叉树排序的思想就是先将待排序序列逐个添加到二叉搜索树中去,再通过中序遍历二叉搜索树就可以将数据从小到大取出来。如果对二叉树还不太了解,请看这篇博文:数据结构和算法之二叉树 ,这里不再赘述。
下面我们来看看二叉树排序的实现:
[java] view
plain copy
public class Tree2Sort {
private Node root;
public Tree2Sort() {
root = null;
}
public Node getRoot() {
return root;
}
public void insertSort(int[] source) {
for(int i = 0; i < source.length; i++) {
int value = source[i];
Node node = new Node(value);
if(root == null) {
root = node;
}
else {
Node current = root;
Node parent;
boolean insertedOK = false;
while(!insertedOK) {
parent = current;
if(value < current.value) {
current = current.leftChild;
if(current == null) {
parent.leftChild = node;
insertedOK = true;
}
}
else {
current = current.rightChild;
if(current == null) {
parent.rightChild = node;
insertedOK = true;
}
}
}
}
}
}
//中序遍历
public void inOrder(Node current) {
if(current != null) {
inOrder(current.leftChild);
System.out.print(current.value + " ");
inOrder(current.rightChild);
}
}
}
class Node {
public int value;
Node leftChild;
Node rightChild;
public Node(int val) {
value = val;
}
}
算法分析:二叉树的插入时间复杂度为O(logN),所以二叉树排序算法的时间复杂度为O(NlogN),但是二叉树排序跟归并排序一样,也需要额外的和待排序序列大小相同的存储空间。空间复杂度为O(N)。
下面我们来看看二叉树排序的实现:
[java] view
plain copy
public class Tree2Sort {
private Node root;
public Tree2Sort() {
root = null;
}
public Node getRoot() {
return root;
}
public void insertSort(int[] source) {
for(int i = 0; i < source.length; i++) {
int value = source[i];
Node node = new Node(value);
if(root == null) {
root = node;
}
else {
Node current = root;
Node parent;
boolean insertedOK = false;
while(!insertedOK) {
parent = current;
if(value < current.value) {
current = current.leftChild;
if(current == null) {
parent.leftChild = node;
insertedOK = true;
}
}
else {
current = current.rightChild;
if(current == null) {
parent.rightChild = node;
insertedOK = true;
}
}
}
}
}
}
//中序遍历
public void inOrder(Node current) {
if(current != null) {
inOrder(current.leftChild);
System.out.print(current.value + " ");
inOrder(current.rightChild);
}
}
}
class Node {
public int value;
Node leftChild;
Node rightChild;
public Node(int val) {
value = val;
}
}
算法分析:二叉树的插入时间复杂度为O(logN),所以二叉树排序算法的时间复杂度为O(NlogN),但是二叉树排序跟归并排序一样,也需要额外的和待排序序列大小相同的存储空间。空间复杂度为O(N)。
相关文章推荐
- 算法14 之归并排序
- CentOS7 PostgreSQL 主从配置( 三)
- 整理:Linux网络编程之sockaddr与sockaddr_in,sockaddr_un结构体详细讲解
- docker学习-简单安装及使用
- Invalid Regular Expression Options
- mysql表的连接方式
- codevs 1242 布局(查分约束+SPFA)
- 对于风行小组第一阶段冲刺成果的概括
- Python常见问题(6):Python在Windows上的问题 Python on Windows FAQ
- eclipse最有用快捷键整理
- 使用Android studio Gradle 实现友盟多渠道打包
- HTML常用属性
- HDU--2033人见人爱A+B
- 不能通过IP地址访问网站的解决方案
- Python常见问题(5):Python扩展与嵌入 Extending/Embedding FAQ
- 算法13 之快速排序
- java学习笔记(十八)
- ssh连接阿里云一段时间不操作自动断开
- pinyin4j使用示例
- SAP 中如何寻找增强