java二叉排序树代码示例
时间: 2023-11-19 19:55:46 浏览: 84
下面是一个Java二叉排序树的代码示例:
```java
public class BinarySortTree {
private Node root;
// 节点类
private class Node {
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// 添加节点
public void addNode(Node node) {
if (root == null) {
root = node;
} else {
Node current = root;
while (true) {
if (node.value < current.value) {
if (current.left == null) {
current.left = node;
break;
} else {
current = current.left;
}
} else {
if (current.right == null) {
current.right = node;
break;
} else {
current = current.right;
}
}
}
}
}
// 中序遍历
public void middleSort() {
middleSort(root);
}
private void middleSort(Node node) {
if (node != null) {
middleSort(node.left);
System.out.print(node.value + " ");
middleSort(node.right);
}
}
// 查找节点
public Node search(int value) {
Node current = root;
while (current != null && current.value != value) {
if (value < current.value) {
current = current.left;
} else {
current = current.right;
}
}
return current;
}
// 删除节点
public void delete(int value) {
root = delete(root, value);
}
private Node delete(Node node, int value) {
if (node == null) {
return null;
}
if (value < node.value) {
node.left = delete(node.left, value);
} else if (value > node.value) {
node.right = delete(node.right, value);
} else {
if (node.left == null) {
return node.right;
} else if (node.right == null) {
return node.left;
}
Node minNode = findMin(node.right);
node.value = minNode.value;
node.right = delete(node.right, minNode.value);
}
return node;
}
private Node findMin(Node node) {
while (node.left != null) {
node = node.left;
}
return node;
}
}
```
阅读全文