📅  最后修改于: 2023-12-03 14:39:35.959000             🧑  作者: Mango
二叉搜索树(Binary Search Tree,BST)是一种常见的数据结构,它具有以下特点:
BST常用来实现关联数组/映射(Map)及集合(Set)。
在Java中,实现BST的方式有多种,以下是一种简单的代码示例:
public class BST<Key extends Comparable<Key>, Value> {
private Node root;
private class Node {
private Key key;
private Value val;
private Node left, right;
private int size;
public Node(Key key, Value val, int size) {
this.key = key;
this.val = val;
this.size = size;
}
}
public int size() {
return size(root);
}
private int size(Node x) {
if (x == null) return 0;
else return x.size;
}
public Value get(Key key) {
return get(root, key);
}
private Value get(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp < 0) return get(x.left, key);
else if (cmp > 0) return get(x.right, key);
else return x.val;
}
public void put(Key key, Value val) {
root = put(root, key, val);
}
private Node put(Node x, Key key, Value val) {
if (x == null) return new Node(key, val, 1);
int cmp = key.compareTo(x.key);
if (cmp < 0) x.left = put(x.left, key, val);
else if (cmp > 0) x.right = put(x.right, key, val);
else x.val = val;
x.size = 1 + size(x.left) + size(x.right);
return x;
}
public void print() {
print(root);
}
private void print(Node x) {
if (x == null) return;
print(x.left);
System.out.println(x.key + " " + x.val);
print(x.right);
}
}
其中,Node
类表示BST的节点,它包含键值对、左右子节点和以该节点为根节点的子树大小。size
方法用于返回以该节点为根节点的子树大小,通过递归实现。get
和put
方法分别实现查找和插入操作。print
方法用于打印BST中所有节点的键值对,使用中序遍历实现。
调用示例:
BST<Integer, String> bst = new BST<Integer, String>();
bst.put(8, "eight");
bst.put(3, "three");
bst.put(1, "one");
bst.put(6, "six");
bst.put(4, "four");
bst.put(7, "seven");
bst.put(10, "ten");
bst.put(14, "fourteen");
bst.put(13, "thirteen");
bst.print();
输出结果:
1 one
3 three
4 four
6 six
7 seven
8 eight
10 ten
13 thirteen
14 fourteen
通过调用print
方法打印出所有节点的键值对,按照升序排列。