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樹的基本功能,包括插入操作和前序遍歷操作。
注意,這只是一個簡單的示例,實際應用中可能需要更多的功能和優化。