#AVL where can I see avl java source code
1 messages · Page 1 of 1 (latest)
<@&987246717831381062> please have a look, thanks.
Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
helpful.
Sure! Here's an implementation of an AVL tree in Java:
class Node {
int key, height;
Node left, right;
Node(int d) {
key = d;
height = 1;
}
}
class AVLTree {
Node root;
int height(Node N) {
if (N == null)
return 0;
return N.height;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
Node rightRotate(Node y) {
Node x = y.left;
Node T2 = x.right;
x.right = y;
y.left = T2;
y.height = max(height(y.left), height(y.right)) + 1;
x.height = max(height(x.left), height(x.right)) + 1;
return x;
}
Node leftRotate(Node x) {
Node y = x.right;
Node T2 = y.left;
y.left = x;
x.right = T2;
x.height = max(height(x.left), height(x.right)) + 1;
y.height = max(height(y.left), height(y.right)) + 1;
return y;
}
int getBalance(Node N) {
if (N == null)
return 0;
return height(N.left) - height(N.right);
}
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;
node.height = 1 + max(height(node.left),height(node.right));
int balanceFactor=getBalance(node);
if (balanceFactor > 1 && key < node.left.key)
return rightRotate(node);
if (balanceFactor < -1 && key > node.right.key)
return leftRotate(node);
if (balanceFactor > 1 && key > node.left.key) {
node.left = leftRotate(node.left);
return rightRotate(node);
}
if (balanceFactor < -1 && key < node.right.key) {
node.right = rightRotate(node.right);
return leftRotate(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);
System.out.println("Preorder traversal of constructed AVL Tree is:");
tree.preOrder(tree.root);
}
}
This implementation includes the basic operations of an AVL Tree such as insertion and rotation. The insert method inserts a new key into the AVL Tree while maintaining its balance. The rightRotate and leftRotate methods perform the necessary rotations to balance the tree. The preOrder method performs a preorder traversal of the AVL Tree.
In the main method, we create an instance of the AVLTree class and insert some keys into it. Finally, we print the preorder traversal of the constructed AVL Tree.
Hope this helps!