Java Program to Implement AVL Tree

This is a Java Program to implement AVL Tree. An AVL tree is a self-balancing binary search tree, and it was the first such data structure to be invented. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. This program is based on the implementation by Mark Allen Weiss.

Here is the source code of the Java program to implement AVL Tree. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /*
  2.  *  Java Program to Implement AVL Tree
  3.  */
  4.  
  5.  import java.util.Scanner;
  6.  
  7.  /* Class AVLNode */
  8.  class AVLNode
  9.  {    
  10.      AVLNode left, right;
  11.      int data;
  12.      int height;
  13.  
  14.      /* Constructor */
  15.      public AVLNode()
  16.      {
  17.          left = null;
  18.          right = null;
  19.          data = 0;
  20.          height = 0;
  21.      }
  22.      /* Constructor */
  23.      public AVLNode(int n)
  24.      {
  25.          left = null;
  26.          right = null;
  27.          data = n;
  28.          height = 0;
  29.      }     
  30.  }
  31.  
  32.  /* Class AVLTree */
  33.  class AVLTree
  34.  {
  35.      private AVLNode root;     
  36.  
  37.      /* Constructor */
  38.      public AVLTree()
  39.      {
  40.          root = null;
  41.      }
  42.      /* Function to check if tree is empty */
  43.      public boolean isEmpty()
  44.      {
  45.          return root == null;
  46.      }
  47.      /* Make the tree logically empty */
  48.      public void makeEmpty()
  49.      {
  50.          root = null;
  51.      }
  52.      /* Function to insert data */
  53.      public void insert(int data)
  54.      {
  55.          root = insert(data, root);
  56.      }
  57.      /* Function to get height of node */
  58.      private int height(AVLNode t )
  59.      {
  60.          return t == null ? -1 : t.height;
  61.      }
  62.      /* Function to max of left/right node */
  63.      private int max(int lhs, int rhs)
  64.      {
  65.          return lhs > rhs ? lhs : rhs;
  66.      }
  67.      /* Function to insert data recursively */
  68.      private AVLNode insert(int x, AVLNode t)
  69.      {
  70.          if (t == null)
  71.              t = new AVLNode(x);
  72.          else if (x < t.data)
  73.          {
  74.              t.left = insert( x, t.left );
  75.              if( height( t.left ) - height( t.right ) == 2 )
  76.                  if( x < t.left.data )
  77.                      t = rotateWithLeftChild( t );
  78.                  else
  79.                      t = doubleWithLeftChild( t );
  80.          }
  81.          else if( x > t.data )
  82.          {
  83.              t.right = insert( x, t.right );
  84.              if( height( t.right ) - height( t.left ) == 2 )
  85.                  if( x > t.right.data)
  86.                      t = rotateWithRightChild( t );
  87.                  else
  88.                      t = doubleWithRightChild( t );
  89.          }
  90.          else
  91.            ;  // Duplicate; do nothing
  92.          t.height = max( height( t.left ), height( t.right ) ) + 1;
  93.          return t;
  94.      }
  95.      /* Rotate binary tree node with left child */     
  96.      private AVLNode rotateWithLeftChild(AVLNode k2)
  97.      {
  98.          AVLNode k1 = k2.left;
  99.          k2.left = k1.right;
  100.          k1.right = k2;
  101.          k2.height = max( height( k2.left ), height( k2.right ) ) + 1;
  102.          k1.height = max( height( k1.left ), k2.height ) + 1;
  103.          return k1;
  104.      }
  105.  
  106.      /* Rotate binary tree node with right child */
  107.      private AVLNode rotateWithRightChild(AVLNode k1)
  108.      {
  109.          AVLNode k2 = k1.right;
  110.          k1.right = k2.left;
  111.          k2.left = k1;
  112.          k1.height = max( height( k1.left ), height( k1.right ) ) + 1;
  113.          k2.height = max( height( k2.right ), k1.height ) + 1;
  114.          return k2;
  115.      }
  116.      /**
  117.       * Double rotate binary tree node: first left child
  118.       * with its right child; then node k3 with new left child */
  119.      private AVLNode doubleWithLeftChild(AVLNode k3)
  120.      {
  121.          k3.left = rotateWithRightChild( k3.left );
  122.          return rotateWithLeftChild( k3 );
  123.      }
  124.      /**
  125.       * Double rotate binary tree node: first right child
  126.       * with its left child; then node k1 with new right child */      
  127.      private AVLNode doubleWithRightChild(AVLNode k1)
  128.      {
  129.          k1.right = rotateWithLeftChild( k1.right );
  130.          return rotateWithRightChild( k1 );
  131.      }    
  132.      /* Functions to count number of nodes */
  133.      public int countNodes()
  134.      {
  135.          return countNodes(root);
  136.      }
  137.      private int countNodes(AVLNode r)
  138.      {
  139.          if (r == null)
  140.              return 0;
  141.          else
  142.          {
  143.              int l = 1;
  144.              l += countNodes(r.left);
  145.              l += countNodes(r.right);
  146.              return l;
  147.          }
  148.      }
  149.      /* Functions to search for an element */
  150.      public boolean search(int val)
  151.      {
  152.          return search(root, val);
  153.      }
  154.      private boolean search(AVLNode r, int val)
  155.      {
  156.          boolean found = false;
  157.          while ((r != null) && !found)
  158.          {
  159.              int rval = r.data;
  160.              if (val < rval)
  161.                  r = r.left;
  162.              else if (val > rval)
  163.                  r = r.right;
  164.              else
  165.              {
  166.                  found = true;
  167.                  break;
  168.              }
  169.              found = search(r, val);
  170.          }
  171.          return found;
  172.      }
  173.      /* Function for inorder traversal */
  174.      public void inorder()
  175.      {
  176.          inorder(root);
  177.      }
  178.      private void inorder(AVLNode r)
  179.      {
  180.          if (r != null)
  181.          {
  182.              inorder(r.left);
  183.              System.out.print(r.data +" ");
  184.              inorder(r.right);
  185.          }
  186.      }
  187.      /* Function for preorder traversal */
  188.      public void preorder()
  189.      {
  190.          preorder(root);
  191.      }
  192.      private void preorder(AVLNode r)
  193.      {
  194.          if (r != null)
  195.          {
  196.              System.out.print(r.data +" ");
  197.              preorder(r.left);             
  198.              preorder(r.right);
  199.          }
  200.      }
  201.      /* Function for postorder traversal */
  202.      public void postorder()
  203.      {
  204.          postorder(root);
  205.      }
  206.      private void postorder(AVLNode r)
  207.      {
  208.          if (r != null)
  209.          {
  210.              postorder(r.left);             
  211.              postorder(r.right);
  212.              System.out.print(r.data +" ");
  213.          }
  214.      }     
  215.  }
  216.  
  217.  /* Class AVL Tree Test */
  218.  public class AVLTreeTest
  219.  {
  220.      public static void main(String[] args)
  221.     {            
  222.         Scanner scan = new Scanner(System.in);
  223.         /* Creating object of AVLTree */
  224.         AVLTree avlt = new AVLTree(); 
  225.  
  226.         System.out.println("AVLTree Tree Test\n");          
  227.         char ch;
  228.         /*  Perform tree operations  */
  229.         do    
  230.         {
  231.             System.out.println("\nAVLTree Operations\n");
  232.             System.out.println("1. insert ");
  233.             System.out.println("2. search");
  234.             System.out.println("3. count nodes");
  235.             System.out.println("4. check empty");
  236.             System.out.println("5. clear tree");
  237.  
  238.             int choice = scan.nextInt();            
  239.             switch (choice)
  240.             {
  241.             case 1 : 
  242.                 System.out.println("Enter integer element to insert");
  243.                 avlt.insert( scan.nextInt() );                     
  244.                 break;                          
  245.             case 2 : 
  246.                 System.out.println("Enter integer element to search");
  247.                 System.out.println("Search result : "+ avlt.search( scan.nextInt() ));
  248.                 break;                                          
  249.             case 3 : 
  250.                 System.out.println("Nodes = "+ avlt.countNodes());
  251.                 break;     
  252.             case 4 : 
  253.                 System.out.println("Empty status = "+ avlt.isEmpty());
  254.                 break;     
  255.             case 5 : 
  256.                 System.out.println("\nTree Cleared");
  257.                 avlt.makeEmpty();
  258.                 break;         
  259.             default : 
  260.                 System.out.println("Wrong Entry \n ");
  261.                 break;   
  262.             }
  263.             /*  Display tree  */ 
  264.             System.out.print("\nPost order : ");
  265.             avlt.postorder();
  266.             System.out.print("\nPre order : ");
  267.             avlt.preorder();
  268.             System.out.print("\nIn order : ");
  269.             avlt.inorder();
  270.  
  271.             System.out.println("\nDo you want to continue (Type y or n) \n");
  272.             ch = scan.next().charAt(0);                        
  273.         } while (ch == 'Y'|| ch == 'y');               
  274.     }
  275.  }

AVLTree Tree Test
 
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
4
Empty status = true
 
Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
10
 
Post order : 10
Pre order : 10
In order : 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
9
 
Post order : 9 10
Pre order : 10 9
In order : 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
8
 
Post order : 8 10 9
Pre order : 9 8 10
In order : 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
7
 
Post order : 7 8 10 9
Pre order : 9 8 7 10
In order : 7 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
6
 
Post order : 6 8 7 10 9
Pre order : 9 7 6 8 10
In order : 6 7 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
5
 
Post order : 5 6 8 10 9 7
Pre order : 7 6 5 9 8 10
In order : 5 6 7 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
4
 
Post order : 4 6 5 8 10 9 7
Pre order : 7 5 4 6 9 8 10
In order : 4 5 6 7 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
3
 
Post order : 3 4 6 5 8 10 9 7
Pre order : 7 5 4 3 6 9 8 10
In order : 3 4 5 6 7 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
2
 
Post order : 2 4 3 6 5 8 10 9 7
Pre order : 7 5 3 2 4 6 9 8 10
In order : 2 3 4 5 6 7 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
1
 
Post order : 1 2 4 6 5 3 8 10 9 7
Pre order : 7 3 2 1 5 4 6 9 8 10
In order : 1 2 3 4 5 6 7 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
0
 
Post order : 0 2 1 4 6 5 3 8 10 9 7
Pre order : 7 3 1 0 2 5 4 6 9 8 10
In order : 0 1 2 3 4 5 6 7 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
3
Nodes = 11
 
Post order : 0 2 1 4 6 5 3 8 10 9 7
Pre order : 7 3 1 0 2 5 4 6 9 8 10
In order : 0 1 2 3 4 5 6 7 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
2
Enter integer element to search
12
Search result : false
 
Post order : 0 2 1 4 6 5 3 8 10 9 7
Pre order : 7 3 1 0 2 5 4 6 9 8 10
In order : 0 1 2 3 4 5 6 7 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
2
Enter integer element to search
4
Search result : true
 
Post order : 0 2 1 4 6 5 3 8 10 9 7
Pre order : 7 3 1 0 2 5 4 6 9 8 10
In order : 0 1 2 3 4 5 6 7 8 9 10
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
5
 
Tree Cleared
 
Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
 
y
 
AVLTree Operations
 
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
4
Empty status = true
 
Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
 
n

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.