Insertion in AVL Tree in Java
Insertion in AVL Tree in Java
Here we will learn about Insertion in AVL Tree in Java, which is an advanced version of BST insertion where the tree automatically maintains balance after every insertion. This ensures that operations like search, insert, and delete always run efficiently.
In this article, we will understand how insertion works in an AVL Tree in Java, including rotations, algorithm, implementation, examples, and best practices.
What is an AVL Tree?
An AVL Tree is a self balancing Binary Search Tree where:
- Difference between heights of left and right subtree (called Balance Factor) is at most 1
Balance Factor = height(left) - height(right)
- If imbalance occurs, rotations are performed to fix it
Why Do We Need AVL Tree Insertion?
Normal BSTs can become skewed (like a linked list), leading to O(n) operations.
AVL Trees ensure:
- Balanced structure
- Faster operations → O(log n)
- Better performance in real world systems like:
- Databases
- Memory indexing
- Search systems
Basic Idea of AVL Insertion:
- Insert node like a normal BST
- Update height of nodes
- Calculate balance factor
- If unbalanced → perform rotation
Types of Rotations in AVL Tree in Java
1. Left Left (LL Rotation)
Occurs when insertion happens in the left subtree of left child.
Before Rotation: After Rotation:
30 20
/ / \
20 → 10 30
/
102. Right Right (RR Rotation)
Occurs when insertion happens in the right subtree of right child.
Before Rotation: After Rotation:
10 20
\ / \
20 → 10 30
\
303. Left Right (LR Rotation)
Occurs when insertion happens in right subtree of left child.
- First left rotate
- Then right rotate
4. Right Left (RL Rotation)
Occurs when insertion happens in left subtree of right child.
- First right rotate
- Then left rotate
Learn DSA
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Insertion and Creation of an AVL Tree
New node can be inserted in an AVL tree by determining the correct position of the node. But insertion of a new node into the tree may affect the height of the tree and the tree might become unbalanced.
- If the new nodes are inserted as child nodes on a non leaf node there will be no alteration since there will be no effect on the balancing as there is no increase in the height of the tree.
- If the new nodes are inserted as child nodes on a leaf node, the balancing of the tree might get distorted. This depends on whether the node is added to the left subtree or the right subtree.
- Thus to re-balance the tree in order to conserve it’s characteristics we use Rotation Mechanism. There are four types of rotations which help maintain the balancing of the tree as specified above.
- If, due to insertion,the b_fact of multiple nodes is disturbed, balancing occurs on the first ancestor of the node that has been inserted.
Note: During the process of insertion it is important to check the balancing factor of each node at each step, until the process end.
Steps for Creating AVL Tree :
Suppose we are given an AVL tree T and N is the new node to be inserted.
- Perform a standard BST insertion of node N in the AVL tree T.
- Starting from node N, traverse up until the first unbalanced node is not found. Let z be the first unbalanced node, y be the child of z that comes on the path from p to z and x be the grandchild of z that comes on the path from p to z.
- Rebalance the tree by performing suitable rotations on the subtree. There can be the following 4 possible cases and after choosing what case is it, we have to do appropriate rotation explained above.
- Left-Left Case – y is left child of z and x is left child of y
- Left-Right Case – y is left child of z and x is the right child of y
- Right-Right Case – y is the right child of z and x is the right child of y
- Right-Left Case – y is the right child of z and x is left child of y
Note: We only need to re-balance the subtree where the first imbalance has occurred using the above cased and the complete tree automatically becomes height-balanced.
Algorithm for Insertion in AVL Tree
Before practicing the Insertion in AVL Tree in Java programming, first we will analyze the Algorithm for Insertion in AVL Tree:
- Perform normal BST insertion
- Update height of current node
- Calculate balance factor
- Check imbalance cases:
- LL → Right rotation
- RR → Left rotation
- LR → Left + Right rotation
- RL → Right + Left rotation
- Return updated node
Java Code for Insertion in AVL Tree
class Node {
int key, height;
Node left, right;
Node(int d) {
key = d;
height = 1;
}
}
public class AVLInsertion {
// Get height
int height(Node N) {
if (N == null)
return 0;
return N.height;
}
// Get balance factor
int getBalance(Node N) {
if (N == null)
return 0;
return height(N.left) - height(N.right);
}
// Right rotation
Node rightRotate(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;
}
// Left rotation
Node leftRotate(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;
}
// Insert function
Node insert(Node node, int key) {
// Step 1: BST insertion
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; // duplicates not allowed
// Step 2: Update height
node.height = 1 + Math.max(height(node.left), height(node.right));
// Step 3: Get balance factor
int balance = getBalance(node);
// Step 4: Rotation cases
// LL Case
if (balance > 1 && key < node.left.key)
return rightRotate(node);
// RR Case
if (balance < -1 && key > node.right.key)
return leftRotate(node);
// LR Case
if (balance > 1 && key > node.left.key) {
node.left = leftRotate(node.left);
return rightRotate(node);
}
// RL Case
if (balance < -1 && key < node.right.key) {
node.right = rightRotate(node.right);
return leftRotate(node);
}
return node;
}
// Preorder traversal
void preorder(Node root) {
if (root != null) {
System.out.print(root.key + " ");
preorder(root.left);
preorder(root.right);
}
}
public static void main(String[] args) {
AVLInsertion tree = new AVLInsertion();
Node root = null;
int[] values = {10, 20, 30, 40, 50, 25};
for (int val : values) {
root = tree.insert(root, val);
}
System.out.print("Preorder Traversal: ");
tree.preorder(root);
}
}
Input:
Insert → 10, 20, 30
Output:
Tree becomes balanced after rotation
2. Insert 20 → OK
3. Insert 30 → imbalance (RR case)
4. Perform left rotation
5. Tree becomes balanced
Space Complexity: O(log n) (recursion stack)
Conclusion:
Common Insights:
- AVL trees strictly maintain balance
- Rotations are key to maintaining efficiency
- Better than BST for worst-case scenarios
- Slightly more overhead than BST
Best Practices:
- Always update height after insertion
- Handle all four rotation cases carefully
- Avoid duplicates unless required
- Test with skewed input
- Use AVL for performance-critical systems
Frequently Asked Questions
Answer:
Insertion in AVL Tree in Java is the process of adding a node while maintaining the height-balanced property using rotations.
Answer:
Because AVL trees prevent skewed structures and guarantee O(log n) time complexity.
Answer:
Rotations are operations (LL, RR, LR, RL) used to balance the tree after insertion.
Answer:
It is O(log n) due to maintained balance.
Answer:
It is used in databases, memory indexing, and systems requiring fast search operations.
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Introduction to Trees
Binary Trees
- Binary Tree in Data Structures (Introduction)
- Tree Traversals: Inorder Postorder Preorder : C | C++ | Java
- Inorder Postorder PreOrder Traversals Examples
- Tree Traversal without Recursion
Binary Search Trees
Traversals
- Traversal in Trees
- Tree Traversals: Breadth-First Search (BFS) : C | C++ | Java
- Tree Traversals: Depth First Search (DFS) : C | C++ | Java
- Construct a Binary Tree from Postorder and Inorder
B – Trees
AVL Trees
- AVL Trees
Complete Programs for Trees
- Depth First Traversals – C | C++ | Java
- Level Order Traversal – C | C++ | Java
- Construct Tree from given Inorder and Preorder traversals – C | C++ | Java
- Construct Tree from given Postorder and Inorder traversals – C | C++ | Java
- Construct Tree from given Postorder and Preorder traversal – C | C++ | Java
- Find size of the Binary tree – C | C++ | Java
- Find the height of binary tree – C | C++ | Java
- Find maximum in binary tree – C | C++ | Java
- Check whether two tree are identical- C| C++| Java
- Spiral Order traversal of Tree- C | C++| Java
- Level Order Traversal LIne by Line – C | C++| Java
- Hand shaking lemma and some Impotant Tree Properties.
- Check If binary tree if Foldable or not.- C| C++| Java
- check whether tree is Symmetric C| C++| Java.
- Check for Children-Sum in Binary Tree- C|C++| Java
- Sum of all nodes in Binary Tree- C | C++ | Java
- Lowest Common Ancestor in Binary Tree. C | C++ | Java
Introduction to Trees
Binary Trees
- Binary Tree in Data Structures (Introduction)
- Tree Traversals: Inorder Postorder Preorder : C | C++ | Java
- Inorder Postorder PreOrder Traversals Examples
- Tree Traversal without Recursion
Binary Search Trees
Traversals
- Traversal in Trees
- Tree Traversals: Breadth-First Search (BFS) : C | C++ | Java
- Tree Traversals: Depth First Search (DFS) : C | C++ | Java
- Construct a Binary Tree from Postorder and Inorder
B – Trees
AVL Trees
- AVL Trees
Complete Programs for Trees
- Depth First Traversals – C | C++ | Java
- Level Order Traversal – C | C++ | Java
- Construct Tree from given Inorder and Preorder traversals – C | C++ | Java
- Construct Tree from given Postorder and Inorder traversals – C | C++ | Java
- Construct Tree from given Postorder and Preorder traversal – C | C++ | Java
- Find size of the Binary tree – C | C++ | Java
- Find the height of binary tree – C | C++ | Java
- Find maximum in binary tree – C | C++ | Java
- Check whether two tree are identical- C| C++| Java
- Spiral Order traversal of Tree- C | C++| Java
- Level Order Traversal Line by Line – C | C++| Java
- Hand shaking lemma and some Impotant Tree Properties.
- Check If binary tree if Foldable or not.- C| C++| Java
- check whether tree is Symmetric – C| C++| Java.
- Check for Children-Sum in Binary Tree- C|C++| Java
- Sum of all nodes in Binary Tree- C | C++ | Java
- Lowest Common Ancestor in Binary Tree- C | C++ | Java

Login/Signup to comment