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

        顾名思义,二叉树排序就是利用二叉搜索树的特点进行排序,前面提到过二叉搜索树的特点是,左子节点比自己小,右子节点比自己大,那么二叉树排序的思想就是先将待排序序列逐个添加到二叉搜索树中去,再通过中序遍历二叉搜索树就可以将数据从小到大取出来。如果对二叉树还不太了解,请看这篇博文:二叉搜索树 ,这里不再赘述。

下面我们来看看二叉树排序的实现:

 

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)。

        

        欢迎大家关注我的公众号:“武哥聊编程”,一个有温度的公众号~

        关注回复:资源,可以领取海量优质视频资料


        程序员私房菜

_____________________________________________________________________________________________________________________________________________________

-----乐于分享,共同进步!

-----更多文章请看:http://blog.csdn.net/eson_15

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值