用java代码实现一个二叉平衡树
时间: 2023-04-06 17:03:43 浏览: 129
java 实现平衡二叉树
好的,我可以回答这个问题。以下是一个简单的 Java 代码实现二叉平衡树的示例:
```
class Node {
int value;
int height;
Node left;
Node right;
Node(int value) {
this.value = value;
this.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);
}
Node rotateRight(Node y) {
Node x = y.left;
Node T2 = x.right;
x.right = y;
y.left = T2;
y.height = Math.max(height(y.left), height(y.right)) + 1;
x.height = Math.max(height(x.left), height(x.right)) + 1;
return x;
}
Node rotateLeft(Node x) {
Node y = x.right;
Node T2 = y.left;
y.left = x;
x.right = T2;
x.height = Math.max(height(x.left), height(x.right)) + 1;
y.height = Math.max(height(y.left), height(y.right)) + 1;
return y;
}
Node insert(Node node, int value) {
if (node == null) {
return new Node(value);
}
if (value < node.value) {
node.left = insert(node.left, value);
} else if (value > node.value) {
node.right = insert(node.right, value);
} else {
return node;
}
node.height = 1 + Math.max(height(node.left), height(node.right));
int balance = balanceFactor(node);
if (balance > 1 && value < node.left.value) {
return rotateRight(node);
}
if (balance < -1 && value > node.right.value) {
return rotateLeft(node);
}
if (balance > 1 && value > node.left.value) {
node.left = rotateLeft(node.left);
return rotateRight(node);
}
if (balance < -1 && value < node.right.value) {
node.right = rotateRight(node.right);
return rotateLeft(node);
}
return node;
}
void preOrder(Node node) {
if (node != null) {
System.out.print(node.value + " ");
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);
System.out.println("Preorder traversal of constructed tree is : ");
tree.preOrder(tree.root);
}
}
```
这个代码实现了一个基本的 AVL 树,包括插入和旋转操作。在 `main` 方法中,我们创建了一个 AVL 树并插入了一些节点,然后使用前序遍历打印出树的结构。
阅读全文