Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
B-Tree in Java
Next article icon

AVL Tree program in Java

Last Updated : 04 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

AVL tree stands for Adelson-Velsky and Landis tree. An AVL tree is a type of self-balancing binary search tree. In an AVL tree, the height of two child subtrees of any of the nodes differs by no more than one, ensuring that the tree remains balanced. This property helps in maintaining the tree's height to O(log n), which ensures efficient operations such as search operation, insertion operation, and deletion operation.

Organization of an AVL Tree

An AVL tree is a type of binary search tree (BST) that maintains its balance through rotations. The key feature of the AVL tree is that for any given node, the height of the left and right subtrees differs by no more than one. This ensures that the tree remains balanced and allows for efficient operations.

Representation of an AVL Tree:

AVL_Tree


Explanation of the Image:

In the above image, an AVL tree is organized to the maintain balance through use of heights and rotations. The key operations are ensure that height difference between subtree of any node is at most one which is keep the tree balanced and operations efficient. Rotations are plays the crucial role in the maintaining this balance after insertion and deletion.

Implementation of an AVL Tree

Java
// Java Program to Implement AVL Tree  class Node {     int key, height;     Node left, right;      Node(int key) {         this.key = key;         this.height = 1;     } }  class AVLTree {      Node root;      // Get the height of the node     int height(Node node) {         if (node == null)             return 0;         return node.height;     }      // Get maximum of two integers     int max(int a, int b) {         return (a > b) ? a : b;     }      // Right rotate subtree rooted with node     Node rightRotate(Node node) {         Node leftChild = node.left;         Node temp = leftChild.right;          // Perform rotation         leftChild.right = node;         node.left = temp;          // Update heights         node.height = max(height(node.left), height(node.right)) + 1;         leftChild.height = max(height(leftChild.left), height(leftChild.right)) + 1;          // Return new root         return leftChild;     }      // Left rotate subtree rooted with node     Node leftRotate(Node node) {         Node rightChild = node.right;         Node temp = rightChild.left;          // Perform rotation         rightChild.left = node;         node.right = temp;          // Update heights         node.height = max(height(node.left), height(node.right)) + 1;         rightChild.height = max(height(rightChild.left), height(rightChild.right)) + 1;          // Return new root         return rightChild;     }      // Get balance factor of node     int getBalance(Node node) {         if (node == null)             return 0;         return height(node.left) - height(node.right);     }      // Insert a key into the AVL tree and return the new root of the subtree     Node insert(Node root, int key) {         if (root == null)             return new Node(key);          if (key < root.key)             root.left = insert(root.left, key);         else if (key > root.key)             root.right = insert(root.right, key);         else             return root;          // Update height of root         root.height = 1 + max(height(root.left), height(root.right));          // Get balance factor         int balance = getBalance(root);          // Left Left Case         if (balance > 1 && key < root.left.key)             return rightRotate(root);          // Right Right Case         if (balance < -1 && key > root.right.key)             return leftRotate(root);          // Left Right Case         if (balance > 1 && key > root.left.key) {             root.left = leftRotate(root.left);             return rightRotate(root);         }          // Right Left Case         if (balance < -1 && key < root.right.key) {             root.right = rightRotate(root.right);             return leftRotate(root);         }          return root;     }      // Utility functions for traversal     void preOrder(Node node) {         if (node != null) {             System.out.print(node.key + " ");             preOrder(node.left);             preOrder(node.right);         }     }      void inOrder(Node node) {         if (node != null) {             inOrder(node.left);             System.out.print(node.key + " ");             inOrder(node.right);         }     }      void postOrder(Node node) {         if (node != null) {             postOrder(node.left);             postOrder(node.right);             System.out.print(node.key + " ");         }     }      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);         System.out.println();          System.out.println("Inorder traversal of constructed AVL tree is : ");         tree.inOrder(tree.root);         System.out.println();          System.out.println("Postorder traversal of constructed AVL tree is : ");         tree.postOrder(tree.root);         System.out.println();     } } 

Output:

Preorder traversal of constructed AVL tree is : 
30 20 10 25 40 50
Inorder traversal of constructed AVL tree is :
10 20 25 30 40 50
Postorder traversal of constructed AVL tree is :
10 25 20 50 40 30


Complexity of the Above Methods

Operations

Explanation

Complexity

Insertion Operation

Insertion operation in AVL tree is involved the binary search tree insertion followed by the re-balanced the tree if it is become unbalanced.

The time complexity of insertion operation is O(log n).
The space complexity of insertion operation is O(1).

Deletion Operation

Deletion operation from the AVL tree is involved the balanced search tree deletion followed by the re-balancing tree if it is becomes unbalanced.

The time complexity of deletion operation is O(log n).
The space complexity of deletion operation is O(1).

Search Operation

Searching operation is involved the searching for the node in the AVL tree is identical to the searching in the BST.

The time complexity of search operation is O(log n).
The space complexity of search operation is O(1).

Traversal Operation

AVL trees supports the standard tree traversal methods such as preorder, inorder and postorder traversals.

The time complexity of traversal operation is O(n).
The space complexity of traversal operation is O(log n).

Applications of an AVL Tree

AVL trees are being balanced binary search trees, it have several practical applications in the computer science and real-world scenarios where the efficient data retrieval and updates are crucial. Here is the some applications of AVL Tree:

  1. Database Indexing
  2. Memory Management
  3. File Systems
  4. Network Routing
  5. Priority Queues
  6. Compiler Design
  7. Geospatial Databases
  8. Event Scheduling Systems
  9. Artificial Intelligence and Machine Learning
  10. Telecommunication Systems

Conclusion

In conclusion, AVL trees are the powerful and versatile data structures that is ensure the efficient and balanced management of the dynamically changing the datasets. Their ability to the maintain the balanced binary search tree guarantees O(log n) time complexity for the insertion operation, deletion operation and search operation and it make them highly suitable for the applications are requiring the frequently updates and fast access times. From the database indexing and memory management to the file systems and network routing. AVL trees are crucial role in the optimizing performance and ensuring the data integrity across the various domains.


Next Article
B-Tree in Java
author
jagan716
Improve
Article Tags :
  • Java
  • Java-DSA
Practice Tags :
  • Java

Similar Reads

  • Java Program to Implement B+ Tree
    The B+ tree is a self-balancing tree data structure commonly used in database and file systems applications. It is an extension of B-Tree and maintains sorted data in a manner that allows us for efficient insertion, deletion and search operations. The B+Trees stores all data in a leaf node while int
    6 min read
  • C Program to Implement AVL Tree
    In C, AVL trees are self-balancing binary search trees. They maintain a balance by ensuring that the difference between the heights of their left subtrees and the right subtrees can be either 0, 1 or -1 and whenever this height property is violated, the tree balances itself using the different rotat
    8 min read
  • C++ Program to Implement AVL Tree
    AVL Tree, named after its inventors Adelson-Velsky and Landis, is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one, which ensures that the tree remains approximately balanced, providing efficient search, insertion, and delet
    11 min read
  • B-Tree in Java
    A B-tree is a self-balanced tree data structure that will maintain the sorted data and allow for operations such as insertion, deletion and search operations. B-tree is particularly well-suited for systems that need to perform disk-based operations and it minimizes the number of disk accesses requir
    6 min read
  • Segment Tree in Java
    A Segment Tree is a binary tree used for storing intervals or segments. It is allowed to query sum, minimum, maximum or other associative operations over the range of elements in the array efficiently. Each node in the segment tree represents the interval of an array. Leaves of the segment tree corr
    6 min read
  • AVL Tree in Python
    The AVL tree in Python is a self–balancing binary search tree that guarantees the difference of the heights of the left and right subtrees of a node is at most 1. The algorithm is named after its inventors, Georgy Adelson-Velsky, and Evgenii Landis who published their paper in 1962. The AVL tree kee
    6 min read
  • TreeSet add() Method in Java
    The Java.util.TreeSet.add() method in Java TreeSet is used to add a specific element into a TreeSet. The function adds the element only if the specified element is not already present in the set else the function return False if the element is not present in the TreeSet. Syntax: Tree_Set.add(Object
    1 min read
  • TreeSet addAll() Method in Java
    The java.util.TreeSet.addAll(Collection C) method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order. Syntax: boolean addAll(Collection C) Parameters: The parameter C is a collection of any typ
    2 min read
  • Java Program to Construct a Binary Search Tree
    Binary Search Tree (BST) is the widely used data structure in computer science, primarily known for the efficient search, insertion, and deletion operations. It is the type of binary tree where each node has at most two children, referred to as the left child and the right child. Binary Search Tree
    6 min read
  • TreeSet in Java
    TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree(red - black tree) for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equ
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences