使用java 写一个红黑树
下面是一个使用Java编写的红黑树的示例代码:
// 定义红黑树节点的颜色
enum Color {
RED,
BLACK
}
// 定义红黑树节点
class Node {
int data;
Color color;
Node left;
Node right;
Node parent;
public Node(int data) {
this.data = data;
this.color = Color.RED;
this.left = null;
this.right = null;
this.parent = null;
}
}
// 定义红黑树
class RedBlackTree {
private Node root;
public RedBlackTree() {
this.root = null;
}
// 左旋操作
private void leftRotate(Node x) {
Node y = x.right;
x.right = y.left;
if (y.left != null) {
y.left.parent = x;
}
y.parent = x.parent;
if (x.parent == null) {
this.root = y;
} else if (x == x.parent.left) {
x.parent.left = y;
} else {
x.parent.right = y;
}
y.left = x;
x.parent = y;
}
// 右旋操作
private void rightRotate(Node x) {
Node y = x.left;
x.left = y.right;
if (y.right != null) {
y.right.parent = x;
}
y.parent = x.parent;
if (x.parent == null) {
this.root = y;
} else if (x == x.parent.right) {
x.parent.right = y;
} else {
x.parent.left = y;
}
y.right = x;
x.parent = y;
}
// 插入操作
public void insert(int data) {
Node newNode = new Node(data);
Node current = this.root;
Node parent = null;
while (current != null) {
parent = current;
if (data < current.data) {
current = current.left;
} else {
current = current.right;
}
}
newNode.parent = parent;
if (parent == null) {
this.root = newNode;
} else if (data < parent.data) {
parent.left = newNode;
} else {
parent.right = newNode;
}
fixInsert(newNode);
}
// 插入后修复红黑树性质
private void fixInsert(Node x) {
while (x != root && x.parent.color == Color.RED) {
if (x.parent == x.parent.parent.left) {
Node y = x.parent.parent.right;
if (y != null && y.color == Color.RED) {
x.parent.color = Color.BLACK;
y.color = Color.BLACK;
x.parent.parent.color = Color.RED;
x = x.parent.parent;
} else {
if (x == x.parent.right) {
x = x.parent;
leftRotate(x);
}
x.parent.color = Color.BLACK;
x.parent.parent.color = Color.RED;
rightRotate(x.parent.parent);
}
} else {
Node y = x.parent.parent.left;
if (y != null && y.color == Color.RED) {
x.parent.color = Color.BLACK;
y.color = Color.BLACK;
x.parent.parent.color = Color.RED;
x = x.parent.parent;
} else {
if (x == x.parent.left) {
x = x.parent;
rightRotate(x);
}
x.parent.color = Color.BLACK;
x.parent.parent.color = Color.RED;
leftRotate(x.parent.parent);
}
}
}
root.color = Color.BLACK;
}
// 中序遍历红黑树
private void inorderTraversal(Node node) {
if (node != null) {
inorderTraversal(node.left);
System.out.print(node.data + " ");
inorderTraversal(node.right);
}
}
public void inorderTraversal() {
inorderTraversal(this.root);
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
RedBlackTree tree = new RedBlackTree();
tree.insert(10);
tree.insert(20);
tree.insert(30);
tree.insert(40);
tree.insert(50);
tree.insert(60);
tree.insert(70);
tree.inorderTraversal(); // 输出:10 20 30 40 50 60 70
}
}
这是一个简单的红黑树实现,包含插入操作和中序遍历操作。在插入操作中,通过左旋和右旋操作来修复红黑树的性质。在中序遍历操作中,按升序输出红黑树中的节点值。在示例中,我们插入了一些节点并进行了中序遍历,输出结果为:10 20 30 40 50 60 70。
原文地址: http://www.cveoy.top/t/topic/ibTX 著作权归作者所有。请勿转载和采集!