Don’t say much, just go to the code.
package org.bood.tree;
/**
* 二分查找树
* ps:如果 data[0] 等于一组数据中最小的,那么就会增加查找的时间复杂度。
* 平衡二叉树(追求极致的平衡),现实需求很难满足,红黑数孕育而生
*
* @author bood
* @since 2020/10/16
*/
public class BinarySearchTree {
/**
* 根节点数
*/
int data;
/**
* 添加一个计数器来记录重复数据的出现次数
*/
int count;
/**
* 左子树
*/
BinarySearchTree left;
/**
* 右子树
*/
BinarySearchTree right;
public BinarySearchTree(int data) {
this.data = data;
// 初始化为1,表示至少有一个这样的值
this.count = 1;
this.left = null;
this.right = null;
}
/**
* 插入新节点到二分查找树
* 如果新节点的值小于当前节点的值,则插入到左子树;
* 如果大于,则插入到右子树;
* 如果等于,可以选择忽略或者记录重复次数。
*
* @param newData 新节点的值
* @author bood
* @since 2024/01/05
*/
public void insert(int newData) {
if (newData > this.data) {
if (this.right == null) {
this.right = new BinarySearchTree(newData);
} else {
this.right.insert(newData);
}
} else if (newData < this.data) {
if (this.left == null) {
this.left = new BinarySearchTree(newData);
} else {
this.left.insert(newData);
}
} else {
// 如果 newData 等于 this.data,增加这个节点的计数
this.count++;
}
}
/**
* 对二分查找树进行中序遍历
* 中序遍历的结果为排序后的节点值
*
* @author bood
* @since 2024/01/05
*/
public void inOrderTraversal() {
if (this.left != null) {
this.left.inOrderTraversal();
}
// 打印节点值及其出现的次数
System.out.print(this.data + "(" + this.count + ") ");
if (this.right != null) {
this.right.inOrderTraversal();
}
}
public static void main(String[] args) {
int[] data = {5, 6, 1, 7, 8, 9, 2, 4, 10};
BinarySearchTree bst = new BinarySearchTree(data[0]);
for (int i = 1; i < data.length; i++) {
bst.insert(data[i]);
}
System.out.println("中序遍历:");
bst.inOrderTraversal();
}
}