BST是一种二叉搜索树的数据结构,它具有以下特点:
- 左子树中的每个节点都小于该节点
- 右子树中的每个节点都大于该节点
- 左子树和右子树都是BST
BST可以用Java的节点类和BST类来实现。BST类中应该包括以下方法:
- insert():插入一个元素到BST中
- search():搜索BST中的一个元素
- traverse():遍历BST
- delete():删除某个元素
以下是一个简单的Java代码例子:
class Node {
int key;
Node left, right;
public Node(int item) {
this.key = item;
this.left = null;
this.right = null;
}
}
public class BST {
Node root;
public BST() {
root = null;
}
public void insert(int key) {
root = insertRec(root, key);
}
Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
return root;
}
public void inorder() {
inorderRec(root);
}
public void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.println(root.key);
inorderRec(root.right);
}
}
}