用java写个红黑二叉树
时间: 2024-06-15 11:02:02 浏览: 113
在Java中,我们可以使用自定义类来实现红黑二叉树(Red-Black Tree)。红黑树是一种自平衡的二叉查找树,每个节点都被标记为红色或黑色,满足以下五个性质:
1. 每个节点是红色或黑色。
2. 根节点是黑色。
3. 每个叶节点(空节点)是黑色。
4. 如果一个节点是红色的,则它的两个子节点都是黑色。
5. 从任一节点到其所有后代叶节点的简单路径上,均包含相同数目的黑色节点。
下面是创建一个简单的红黑树节点和类的示例:
```java
public class Node {
int key;
boolean color; // red or black
Node left, right, parent;
// constructor and getters/setters...
}
public class RedBlackTree {
private Node root;
private boolean isRootRed; // to check if root is red
// methods for insertion, deletion, balancing (rotate and color flips)
public void insert(int key) {
root = insert(root, key);
}
private Node insert(Node node, int key) {
// ...insertion logic with proper coloring and balancing
}
public void delete(int key) {
root = delete(root, key);
}
private Node delete(Node node, int key) {
// ...deletion logic with balancing after removing a node
}
// helper methods for checking balance and rebalancing
private boolean isBalanced(Node node) {
// ...implementation of the balance check
}
private void rotateLeft(Node node) {
// ...implementation of left rotation
}
private void rotateRight(Node node) {
// ...implementation of right rotation
}
private void flipColors(Node node) {
// ...implementation of color flipping
}
}
```
阅读全文