【数据结构和算法15】二叉树排序
来源:互联网 发布:手机淘宝一元起拍在哪 编辑:程序博客网 时间:2024/05/16 06:10
顾名思义,二叉树排序就是利用二叉搜索树的特点进行排序,前面提到过二叉搜索树的特点是,左子节点比自己小,右子节点比自己大,那么二叉树排序的思想就是先将待排序序列逐个添加到二叉搜索树中去,再通过中序遍历二叉搜索树就可以将数据从小到大取出来。如果对二叉树还不太了解,请看这篇博文:二叉搜索树 ,这里不再赘述。
下面我们来看看二叉树排序的实现:
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)。
_____________________________________________________________________________________________________________________________________________________
-----乐于分享,共同进步!
4 0
- 【数据结构和算法15】二叉树排序
- 数据结构和算法二叉树排序
- 数据结构复习:几种排序算法的C++实现和二叉树的相关算法实现
- 数据结构中排序算法- 二叉树排序(7)
- 数据结构和算法系列课程(01)--- 排序二叉树和红黑树
- 数据结构和算法系列15 线索二叉树
- 数据结构和算法系列15 线索二叉树
- 数据结构和算法——二叉排序(查找)树及实现
- 算法基础---数据结构---树和二叉树
- 数据结构-排序二叉树
- 数据结构和算法系列14 二叉树
- 浅谈算法和数据结构: 二叉查找树
- 二叉树 – 数据结构和算法43
- 算法和数据结构: 二叉查找树
- 浅谈数据结构和算法:二叉树
- 数据结构和算法一:平衡二叉树
- 数据结构和算法系列之 二叉树
- 数据结构和算法——二叉树
- 关于在牛客网上做题的解析之数据结构(每日20道题,记录错误和不懂的题)
- 1、SDK、目录结构、adb命令、事件写法
- 顺序表的查找
- [iOS]编译报错:ld: symbol(s) not found for architecture x86_64
- 校园网免流量看视频,上谷歌,脸书,推特
- 【数据结构和算法15】二叉树排序
- java常用类
- FJNUOJ1159
- MapReduce源码分析之InputFormat
- hihoCoder--1268--九宫(全排列)
- [poj 3140] Contestants Division 树形DP
- hiho 35 二分图三·二分图最小点覆盖和最大独立集
- FZU 1914 Funny Positive Sequence
- 华为二面---华丽的扑街