下面是一个用Java实现的二叉搜索树(Binary Search Tree, BST)的示例。该实现包括基本的插入、查找和中序遍历功能,并且附带注释以便理解。
二叉搜索树简介
二叉搜索树是一种特殊的二叉树,其中每个节点满足以下性质:
左子树上的所有节点的值均小于当前节点的值。
右子树上的所有节点的值均大于当前节点的值。
每个子树同样满足以上两个性质。
这种结构使得查找、插入和删除操作的时间复杂度平均为O(log n),适用于动态数据集。
Java实现
以下是一个简单的二叉搜索树的实现:
// 定义二叉搜索树节点
class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
left = right = null;
}
}
// 二叉搜索树类
public class BinarySearchTree {
private TreeNode root;
public BinarySearchTree() {
root = null;
}
// 插入一个值到BST
public void insert(int value) {
root = insertRec(root, value);
}
// 递归插入节点
private TreeNode insertRec(TreeNode root, int value) {
// 如果树为空,新节点就是根节点
if (root == null) {
root = new TreeNode(value);
return root;
}
// 否则,递归下去
if (value < root.value) {
root.left = insertRec(root.left, value);
} else if (value > root.value) {
root.right = insertRec(root.right, value);
}
// 如果值已经存在,不做任何操作
retu