您的位置:首页 > 理论基础 > 数据结构算法

数据结构和算法二叉树排序

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: