二叉排序树(Java实现)

存储元素的方式比较

  • 数组
  1. 数组未排序
    优点:直接在数组末尾添加。速度快 缺点:查找慢
  2. 数组排序
    优点:可以使用二分查找速度比较快 缺点:为了保证数组有序,在添加新元素时找到插入位置后 后面的数据要整体移动速度慢。
  • 链表

不管链表是否有序,查找速度都慢,添加数据速度比数组快,不需要数据整体移动。

在这里插入图片描述
二叉排序树介绍:(BST)[Binary Sort Tree]d=对于二叉排序树的任何一个非叶子节点,要求左子节点的值比当前节点的值小,右子节点的值比当前节点的值大。
如果有相同的值既可以放在左边又可以放在右边。


这是二叉排序树思想的添加元素的代码

// 判断传入的节点的值,和当前子树的根节点的值的关系
	public void add(Node node) {
		if (node == null) {
			return;
		}
		// 判断当前传入的值和与当前节点的值的关系
		if (node.value < this.value) {

			if (this.left == null) {
				this.left = node;
			} else {
				this.left.add(node);
			}

		} else {

			if (this.right == null) {
				this.right = node;
			} else {
				this.right.add(node);
			}

		}

	}


这是整体代码
package bstTree;

public class BinarysortTreeTest {
	public static void main(String[] args) {
		// 测试
		BinarySortTree2 bst2 = new BinarySortTree2(null);
		int[] arr = new int[10000000];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = (int) ((Math.random() * 90000) + 20);
		}
		// 开始排序时间
		long start = System.currentTimeMillis();
		System.out.println(start);
		for (int i = 0; i < arr.length; i++) {
			bst2.add(new Node(arr[i]));
		}
		long end = System.currentTimeMillis();
		System.out.println((end-start ) + "毫秒");

		// 遍历
		//bst2.infixOder();

	}
}

//这是一颗二叉排序树
class BinarySortTree2 {
	Node root;

	public BinarySortTree2(Node root) {
		this.root = root;
	}

	// 添加
	public void add(Node node) {
		if (root == null) {
			root = node;
		} else {
			root.add(node);
		}
	}

	// 遍历
	public void infixOder() {

		if (root == null) {
			System.out.println("这个节点为空");

		} else {
			root.infixOrder();
		}

	}

}
//建立树的节点

class Node2 {
	int value;
	Node left;
	Node right;

	public Node2(int value) {
		this.value = value;
	}

	// 遍历
	public void infixOrder() {
		if (this.left != null) {
			this.left.infixOrder();
		}
		System.out.println(this.value);
		if (this.right != null) {
			this.right.infixOrder();
		}
	}

	// 添加

	public void add(Node node) {
		if (node == null) {
			return;
		}
		if (this.value > node.value) {
			// 如果这个节点的左子节点为空,那么就直接挂在节点的左侧
			if (this.left == null) {
				this.left = node;
			} else {
				this.left.add(node);
			}
		} else {
			// 如果这个节点的值大于这个头节点
			if (this.right == null) {
				this.right = node;
			} else {
				this.right.add(node);
			}
		}

	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

理想艺术!马

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值