数据结构和算法二叉树排序
2016-04-22 09:58
357 查看
顾名思义,二叉树排序就是利用二叉搜索树的特点进行排序,前面提到过二叉搜索树的特点是,左子节点比自己小,右子节点比自己大,那么二叉树排序的思想就是先将待排序序列逐个添加到二叉搜索树中去,再通过中序遍历二叉搜索树就可以将数据从小到大取出来。算法分析:二叉树的插入时间复杂度为O(logN),所以二叉树排序算法的时间复杂度为O(NlogN),但是二叉树排序跟归并排序一样,也需要额外的和待排序序列大小相同的存储空间。空间复杂度为O(N)。
下面我们来看看二叉树排序的实现:
下面我们来看看二叉树排序的实现:
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; } }
相关文章推荐
- 简单数据结构---数组实现栈
- 数据结构与算法--查找与排序(二)
- 数据结构与算法--查找与排序(一)
- 数据结构与算法--二叉树(二)
- 数据结构与算法--二叉树(一)
- 数据结构与算法--链表C++实现
- 数据结构与算法--线性表
- 数据结构与算法--顺序表
- 图的数据结构实现
- [数据结构]链表操作
- linux内存管理之数据结构
- 数据结构简单调试
- 数据结构之物流信息的归并排序(非递归实现)
- 数据结构---二叉树
- 数据结构之二叉树 (构造 拷贝构造 以及前序中序后续三种遍历方法)
- 大话数据结构读书笔记系列(六)树<上篇>
- 数据结构求一个矩阵的马鞍点
- 【数据结构】堆栈、队列的原理及java实现
- Android JNI 使用的数据结构JNINativeMethod详解
- 数据结构-树状数组讲解