Java中可以使用AVL树来实现平衡二叉树。AVL树是一种自平衡二叉搜索树,它的每个节点的左子树和右子树的高度最多相差1。
以下是一个简单的AVL树的实现示例:
class Node {
int key, height;
Node left, right;
Node(int value) {
key = value;
height = 1;
}
}
class AVLTree {
Node root;
int height(Node node) {
if (node == null)
return 0;
return node.height;
}
int balanceFactor(Node node) {
if (node == null)
return 0;
return height(node.left) - height(node.right);
}
void updateHeight(Node node) {
node.height = Math.max(height(node.left), height(node.right)) + 1;
}
Node rotateRight(Node y) {
Node x = y.left;
Node T2 = x.right;
x.right = y;
y.left = T2;
updateHeight(y);
updateHeight(x);
return x;
}
Node rotateLeft(Node x) {
Node y = x.right;
Node T2 = y.left;
y.left = x;
x.right = T2;
updateHeight(x);
updateHeight(y);
return y;
}
Node insert(Node node, int key) {
if (node == null)
return new Node(key);
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
else
return node;
updateHeight(node);
int balance = balanceFactor(node);
// Left Left Case
if (balance > 1 && key < node.left.key)
return rotateRight(node);
// Right Right Case
if (balance < -1 && key > node.right.key)
return rotateLeft(node);
// Left Right Case
if (balance > 1 && key > node.left.key) {
node.left = rotateLeft(node.left);
return rotateRight(node);
}
// Right Left Case
if (balance < -1 && key < node.right.key) {
node.right = rotateRight(node.right);
return rotateLeft(node);
}
return node;
}
void preOrder(Node node) {
if (node != null) {
System.out.print(node.key + " ");
preOrder(node.left);
preOrder(node.right);
}
}
public static void main(String[] args) {
AVLTree tree = new AVLTree();
tree.root = tree.insert(tree.root, 10);
tree.root = tree.insert(tree.root, 20);
tree.root = tree.insert(tree.root, 30);
tree.root = tree.insert(tree.root, 40);
tree.root = tree.insert(tree.root, 50);
tree.root = tree.insert(tree.root, 25);
tree.preOrder(tree.root);
}
}
上述示例实现了AVL树的基本功能,包括插入操作和前序遍历操作。
注意,这只是一个简单的示例,实际应用中可能需要更多的功能和优化。