存储元素的方式比较
- 数组
- 数组未排序
优点:直接在数组末尾添加。速度快 缺点:查找慢- 数组排序
优点:可以使用二分查找速度比较快 缺点:为了保证数组有序,在添加新元素时找到插入位置后 后面的数据要整体移动速度慢。
- 链表
不管链表是否有序,查找速度都慢,添加数据速度比数组快,不需要数据整体移动。
二叉排序树介绍:(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);
}
}
}
}