C++ Program to Check if a Binary Tree is an AVL Tree or Not

This is a C++ Program to check if BST is AVL. An AVL tree is a self-balancing binary search tree. 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.
A tree is AVL if and only if it is Binary Search Tree and is Balanced.

Here is source code of the C++ Program to Check if a Given Binary Tree is an AVL Tree or Not. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

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

Output:

$ g++ CheckAVL.cpp
$ a.out
 
SelfBalancingBinarySearchTree Test
 
SelfBalancingBinarySearchTree Operations
1. Insert
2. Count nodes
3. Search
4. Check empty
5. Make empty
Enter your Choice: 1
Enter integer element to insert: 5
 
Post order : 5
Pre order : 5
In order : 5
Do you want to continue (Type y or n): y
 
SelfBalancingBinarySearchTree Operations
1. Insert
2. Count nodes
3. Search
4. Check empty
5. Make empty
Enter your Choice: 1
Enter integer element to insert: 8
 
Post order : 8  5
Pre order : 5  8
In order : 5  8
Do you want to continue (Type y or n): y
 
SelfBalancingBinarySearchTree Operations
1. Insert
2. Count nodes
3. Search
4. Check empty
5. Make empty
Enter your Choice: 1
Enter integer element to insert: 24
 
Post order : 5  24  8
Pre order : 8  5  24
In order : 5  8  24
Do you want to continue (Type y or n): y
 
SelfBalancingBinarySearchTree Operations
1. Insert
2. Count nodes
3. Search
4. Check empty
5. Make empty
Enter your Choice: 1
Enter integer element to insert: 6
 
Post order : 6  5  24  8
Pre order : 8  5  6  24
In order : 5  6  8  24
Do you want to continue (Type y or n): y
 
SelfBalancingBinarySearchTree Operations
1. Insert
2. Count nodes
3. Search
4. Check empty
5. Make empty
Enter your Choice: 1
Enter integer element to insert: 10
 
Post order : 6  5  10  24  8
Pre order : 8  5  6  24  10
In order : 5  6  8  10  24
Do you want to continue (Type y or n): y
 
SelfBalancingBinarySearchTree Operations
1. Insert
2. Count nodes
3. Search
4. Check empty
5. Make empty
Enter your Choice: 2
Nodes = 5
 
Post order : 6  5  10  24  8
Pre order : 8  5  6  24  10
In order : 5  6  8  10  24
Do you want to continue (Type y or n): y
 
SelfBalancingBinarySearchTree Operations
1. Insert
2. Count nodes
3. Search
4. Check empty
5. Make empty
Enter your Choice: 3
Enter integer element to search: 6
6 found in the tree
 
Post order : 6  5  10  24  8
Pre order : 8  5  6  24  10
In order : 5  6  8  10  24
Do you want to continue (Type y or n): y
 
SelfBalancingBinarySearchTree Operations
1. Insert
2. Count nodes
3. Search
4. Check empty
5. Make empty
Enter your Choice: 5
 
Tree cleared
 
Post order :
Pre order :
In order :
Do you want to continue (Type y or n): y
 
SelfBalancingBinarySearchTree Operations
1. Insert
2. Count nodes
3. Search
4. Check empty
5. Make empty
Enter your Choice: 4
Empty status = Tree is empty
 
Post order :
Pre order :
In order :
Do you want to continue (Type y or n): n
------------------
(program exited with code: 0)
Press return to continue

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement

Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.

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.