{"id":548,"date":"2024-10-19T13:53:50","date_gmt":"2024-10-19T08:23:50","guid":{"rendered":"https:\/\/codexplained.in\/?p=548"},"modified":"2025-11-24T15:32:14","modified_gmt":"2025-11-24T10:02:14","slug":"implement-binary-search-tree","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=548","title":{"rendered":"Implement Binary Search 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 node in the BST\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 insert a new node in the BST\nstruct Node* insert(struct Node* root, int data) {\n    if (root == NULL) {\n        return createNode(data);\n    }\n\n    if (data &lt; root-&gt;data) {\n        root-&gt;left = insert(root-&gt;left, data);\n    } else if (data &gt; root-&gt;data) {\n        root-&gt;right = insert(root-&gt;right, data);\n    }\n\n    return root;\n}\n\n\/\/ Function to perform in-order traversal (left, root, right)\nvoid inOrder(struct Node* root) {\n    if (root != NULL) {\n        inOrder(root-&gt;left);\n        printf(&quot;%d &quot;, root-&gt;data);\n        inOrder(root-&gt;right);\n    }\n}\n\n\/\/ Function to search for a value in the BST\nstruct Node* search(struct Node* root, int key) {\n    if (root == NULL || root-&gt;data == key) {\n        return root;\n    }\n\n    if (key &lt; root-&gt;data) {\n        return search(root-&gt;left, key);\n    }\n\n    return search(root-&gt;right, key);\n}\n\n\/\/ Function to find the minimum value node in a BST\nstruct Node* findMin(struct Node* node) {\n    struct Node* current = node;\n\n    while (current &amp;&amp; current-&gt;left != NULL) {\n        current = current-&gt;left;\n    }\n\n    return current;\n}\n\n\/\/ Function to delete a node from the BST\nstruct Node* deleteNode(struct Node* root, int key) {\n    if (root == NULL) {\n        return root;\n    }\n\n    \/\/ Recur down the tree\n    if (key &lt; root-&gt;data) {\n        root-&gt;left = deleteNode(root-&gt;left, key);\n    } else if (key &gt; root-&gt;data) {\n        root-&gt;right = deleteNode(root-&gt;right, key);\n    } else {\n        \/\/ Node to be deleted found\n\n        \/\/ Node with only one child or no child\n        if (root-&gt;left == NULL) {\n            struct Node* temp = root-&gt;right;\n            free(root);\n            return temp;\n        } else if (root-&gt;right == NULL) {\n            struct Node* temp = root-&gt;left;\n            free(root);\n            return temp;\n        }\n\n        \/\/ Node with two children: Get the inorder successor\n        struct Node* temp = findMin(root-&gt;right);\n\n        \/\/ Copy the inorder successor&#039;s data to this node\n        root-&gt;data = temp-&gt;data;\n\n        \/\/ Delete the inorder successor\n        root-&gt;right = deleteNode(root-&gt;right, temp-&gt;data);\n    }\n\n    return root;\n}\n\n\/\/ Main function to test the BST\nint main() {\n    struct Node* root = NULL;\n\n    \/\/ Insert nodes into the BST\n    root = insert(root, 50);\n    root = insert(root, 30);\n    root = insert(root, 20);\n    root = insert(root, 40);\n    root = insert(root, 70);\n    root = insert(root, 60);\n    root = insert(root, 80);\n\n    printf(&quot;In-order traversal of the BST: &quot;);\n    inOrder(root);\n    printf(&quot;\\n&quot;);\n\n    \/\/ Search for a value\n    int key = 40;\n    struct Node* foundNode = search(root, key);\n    if (foundNode != NULL) {\n        printf(&quot;Node %d found in the BST.\\n&quot;, key);\n    } else {\n        printf(&quot;Node %d not found in the BST.\\n&quot;, key);\n    }\n\n    \/\/ Delete a node\n    root = deleteNode(root, 20);\n    printf(&quot;In-order traversal after deleting 20: &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:<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Structure Definition<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>struct Node<\/code>: Represents a node of the BST. It contains:\n<ul class=\"wp-block-list\">\n<li><code>data<\/code>: The value of 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>Creating a Node<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>createNode(int data)<\/code>: Allocates memory for a new node, sets its data, and initializes left and right pointers to <code>NULL<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Inserting a Node<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>insert(struct Node* root, int data)<\/code>: Recursively inserts a new node:\n<ul class=\"wp-block-list\">\n<li>If <code>root<\/code> is <code>NULL<\/code>, the new node is inserted at this position.<\/li>\n\n\n\n<li>If <code>data<\/code> is less than the current node&#8217;s data, it is inserted in the left subtree.<\/li>\n\n\n\n<li>If <code>data<\/code> is greater, it is inserted in the right subtree.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>In-order Traversal<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>inOrder(struct Node* root)<\/code>: Prints nodes in ascending order by recursively visiting the left subtree, root, and then the right subtree.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Searching<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>search(struct Node* root, int key)<\/code>: Recursively searches for <code>key<\/code>:\n<ul class=\"wp-block-list\">\n<li>If <code>key<\/code> matches the current node\u2019s data, it is found.<\/li>\n\n\n\n<li>If <code>key<\/code> is less, search the left subtree.<\/li>\n\n\n\n<li>If <code>key<\/code> is greater, search the right subtree.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Deleting a Node<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>deleteNode(struct Node* root, int key)<\/code>: Removes a node while maintaining BST properties:\n<ul class=\"wp-block-list\">\n<li>Searches for the <code>key<\/code> to delete.<\/li>\n\n\n\n<li>Handles three cases:\n<ul class=\"wp-block-list\">\n<li>Node with only one child or no child.<\/li>\n\n\n\n<li>Node with two children: Replaces the node with its in-order successor (minimum node from the right subtree).<\/li>\n<\/ul>\n<\/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>Tests the BST by inserting nodes, performing an in-order traversal, searching for a value, deleting a node, and displaying the modified tree.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>In-order traversal of the BST: 20 30 40 50 60 70 80 \nNode 40 found in the BST.\nIn-order traversal after deleting 20: 30 40 50 60 70 80 <\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation of Output:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>In-order Traversal<\/strong>: Displays the BST elements in sorted order.<\/li>\n\n\n\n<li><strong>Node 40 found<\/strong>: Indicates that the search operation successfully located the node with value <code>40<\/code>.<\/li>\n\n\n\n<li><strong>After Deletion<\/strong>: Shows the in-order traversal after deleting the node with value <code>20<\/code>.<\/li>\n<\/ul>\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: Explanation of Output:<\/p>\n","protected":false},"author":40,"featured_media":567,"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-548","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\/548","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=548"}],"version-history":[{"count":5,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/548\/revisions"}],"predecessor-version":[{"id":1386,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/548\/revisions\/1386"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/567"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=548"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=548"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=548"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}