java三叉链表存储二叉排序树并进行增删查改操作
时间: 2023-06-27 22:07:30 浏览: 109
Java三叉链表是指每个节点有三个链接,分别指向父节点、左子节点和右子节点,可以用来存储二叉排序树。下面是基于Java三叉链表实现二叉排序树的增删查改操作的示例代码:
```java
public class BinarySearchTree {
private Node root;
private class Node {
int key;
Node parent;
Node left;
Node right;
public Node(int key, Node parent, Node left, Node right) {
this.key = key;
this.parent = parent;
this.left = left;
this.right = right;
}
}
// 查找
public Node search(int key) {
Node current = root;
while (current != null && current.key != key) {
if (key < current.key) {
current = current.left;
} else {
current = current.right;
}
}
return current;
}
// 插入
public void insert(int key) {
Node parent = null;
Node current = root;
while (current != null) {
parent = current;
if (key < current.key) {
current = current.left;
} else {
current = current.right;
}
}
Node node = new Node(key, parent, null, null);
if (parent == null) {
root = node;
} else if (key < parent.key) {
parent.left = node;
} else {
parent.right = node;
}
}
// 删除
public void delete(int key) {
Node node = search(key);
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
if (node == root) {
root = null;
} else if (node == node.parent.left) {
node.parent.left = null;
} else {
node.parent.right = null;
}
} else if (node.left != null && node.right != null) {
Node successor = minimum(node.right);
node.key = successor.key;
delete(successor.key);
} else {
Node child = (node.left != null) ? node.left : node.right;
if (node == root) {
root = child;
} else if (node == node.parent.left) {
node.parent.left = child;
} else {
node.parent.right = child;
}
child.parent = node.parent;
}
}
// 最小值
public Node minimum(Node node) {
while (node.left != null) {
node = node.left;
}
return node;
}
// 最大值
public Node maximum(Node node) {
while (node.right != null) {
node = node.right;
}
return node;
}
}
```
其中,search() 方法用于查找节点,insert() 方法用于插入节点,delete() 方法用于删除节点,minimum() 方法用于查找最小节点,maximum() 方法用于查找最大节点。这些方法都是基于二叉排序树的性质实现的。
阅读全文