{"id":4857,"date":"2023-06-23T16:22:36","date_gmt":"2023-06-23T10:52:36","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=4857"},"modified":"2023-06-23T17:40:42","modified_gmt":"2023-06-23T12:10:42","slug":"delete-node-from-binary-search-tree","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/delete-node-from-binary-search-tree\/","title":{"rendered":"Delete Node From Binary Search Tree"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"gutentoc tocactive nostyle\"><div class=\"gutentoc-toc-wrap\"><div class=\"gutentoc-toc-title-wrap\"><div class=\"gutentoc-toc-title\">Table Of Contents<\/div><div id=\"open\" class=\"text_open\">show<\/div><\/div><div id=\"toclist\"><div class=\"gutentoc-toc__list-wrap\"><ul class=\"gutentoc-toc__list\"><li><a href=\"#problem-statement\">Problem Statement<\/a><\/li><li><a href=\"#approach-recursion\">Approach: Recursion<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#case-1\">Case 1:<\/a><\/li><li><a href=\"#case-2\">Case 2:<\/a><\/li><li><a href=\"#case-3\">Case 3:<\/a><\/li><\/ul><li><a href=\"#implementation\">Implementation<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code\">C++ Code<\/a><\/li><li><a href=\"#java-code\">Java Code<\/a><\/li><li><a href=\"#python-code\">Python Code<\/a><\/li><\/ul><li><a href=\"#faqs\">FAQs<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#q1-why-is-the-time-complexity-logn\">Q.1: Why is the time complexity log(N)?<\/a><\/li><li><a href=\"#q2-what-is-the-most-efficient-approach-to-solving-this-problem\">Q.2: What is the most efficient approach to solving this problem?<\/a><\/li><\/ul><\/ul><\/div><\/div><\/div><\/div>\n\n\n\n<h2 id=\"problem-statement\">Problem Statement<\/h2>\n\n\n\n<p>Given a binary search tree and a key value. The task is to delete the given key from the BST and return the updated root node.<\/p>\n\n\n\n<p><strong>Examples:<\/strong><br><strong>Input:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"386\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5102 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input1-1024x386.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input1-1024x386.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input1-300x113.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input1-768x290.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input1-1536x579.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input1-2048x772.png 2048w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input1-380x143.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input1-550x207.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input1-800x302.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input1-1160x437.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Input1.png 3339w\" ><\/figure>\n\n\n\n<p><strong>Key =<\/strong> 3<br><strong>Output:<\/strong> Shown in the image<\/p>\n\n\n\n<h2 id=\"approach-recursion\">Approach: Recursion<\/h2>\n\n\n\n<p>If you observe clearly, there are mainly three possible conditions.<\/p>\n\n\n\n<h3 id=\"case-1\">Case 1:<\/h3>\n\n\n\n<ul><li>If the key to be deleted is a leaf node:<ul><li>In this case, simply make the node NULL.<\/li><\/ul><\/li><\/ul>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"645\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5103 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Recursion-Ex-1024x645.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Recursion-Ex-1024x645.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Recursion-Ex-300x189.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Recursion-Ex-768x484.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Recursion-Ex-1536x967.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Recursion-Ex-2048x1290.png 2048w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Recursion-Ex-380x239.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Recursion-Ex-550x346.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Recursion-Ex-800x504.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Recursion-Ex-1160x731.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/Recursion-Ex.png 3539w\" ><\/figure>\n\n\n\n<h3 id=\"case-2\">Case 2:<\/h3>\n\n\n\n<ul><li>If the key to be deleted is not a leaf and has the right child.<ul><li>In this case, replace the node with its successor node.<\/li><\/ul><\/li><\/ul>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"401\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5104 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-5-1024x401.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-5-1024x401.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-5-300x117.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-5-768x301.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-5-1536x602.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-5-2048x802.png 2048w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-5-380x149.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-5-550x215.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-5-800x313.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-5-1160x454.png 1160w\" ><\/figure>\n\n\n\n<h3 id=\"case-3\">Case 3:<\/h3>\n\n\n\n<ul><li>If the key to be deleted is not a leaf and has a left child and no right child.<ul><li>In this case, replace the node with its predecessor node.<\/li><\/ul><\/li><\/ul>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"418\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5105 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image4-1-1024x418.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image4-1-1024x418.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image4-1-300x122.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image4-1-768x314.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image4-1-1536x627.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image4-1-2048x836.png 2048w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image4-1-380x155.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image4-1-550x225.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image4-1-800x327.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image4-1-1160x474.png 1160w\" ><\/figure>\n\n\n\n<p><strong>Algorithm<\/strong><\/p>\n\n\n\n<ul><li>Compare the value of the <strong>key<\/strong> with the <strong>value<\/strong> of the root. If the key > root -> value, recursively traverse the right subtree.<\/li><li>If key &lt; root -> value, recursively traverse the left subtree.<\/li><li>While traversing if key == root->value, we need to delete this node:<ul><li>If the node is a leaf, make root = NULL.<\/li><li>If the node is not a leaf and has the right child, recursively replace its value with the successor node and delete its successor from its original position.<\/li><li>If the node is not a leaf and has a left child, but not a right child, recursively replace its value with a predecessor node and delete its predecessor from its original position.<\/li><\/ul><\/li><li>Return root<\/li><\/ul>\n\n\n\n<h2 id=\"implementation\">Implementation<\/h2>\n\n\n\n<h3 id=\"c-code\">C++ Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">int successor(TreeNode * root) {\n  root = root -> right;\n  while (root -> left != NULL) root = root -> left;\n  return root -> val;\n}\nint predecessor(TreeNode * root) {\n  root = root -> left;\n  while (root -> right != NULL) root = root -> right;\n  return root -> val;\n}\n \nTreeNode * deleteNode(TreeNode * root, int key) {\n  if (root == NULL) return NULL;\n  if (key > root -> val) root -> right = deleteNode(root -> right, key);\n  else if (key &lt; root -> val) root.left = deleteNode(root -> left, key);\n  else {\n    if (root -> left == NULL &amp;&amp; root -> right == NULL) root = NULL;\n    else if (root -> right != NULL) {\n      root -> val = successor(root);\n      root.right = deleteNode(root -> right, root -> val);\n    } else {\n      root -> val = predecessor(root);\n      root -> left = deleteNode(root -> left, root -> val);\n    }\n  }\n  return root;\n}<\/pre>\n\n\n\n<h3 id=\"java-code\">Java Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">int successor(TreeNode * root) {\n  root = root -> right;\n  while (root -> left != NULL) root = root -> left;\n  return root -> val;\n}\nint predecessor(TreeNode * root) {\n  root = root -> left;\n  while (root -> right != NULL) root = root -> right;\n  return root -> val;\n}\n \nTreeNode * deleteNode(TreeNode * root, int key) {\n  if (root == NULL) return NULL;\n  if (key > root -> val) root -> right = deleteNode(root -> right, key);\n  else if (key &lt; root -> val) root.left = deleteNode(root -> left, key);\n  else {\n    if (root -> left == NULL &amp;&amp; root -> right == NULL) root = NULL;\n    else if (root -> right != NULL) {\n      root -> val = successor(root);\n      root.right = deleteNode(root -> right, root -> val);\n    } else {\n      root -> val = predecessor(root);\n      root -> left = deleteNode(root -> left, root -> val);\n    }\n  }\n  return root;\n}\n}<\/pre>\n\n\n\n<h3 id=\"python-code\">Python Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class Solution:\n    def successor(self, root):\n        root = root.right\n        while root.left:\n            root = root.left\n        return root.val\n \n    def predecessor(self, root):\n        root = root.left\n        while root.right:\n            root = root.right\n        return root.val\n \n    def deleteNode(self, root: TreeNode, key: int) -> TreeNode:\n        if not root:\n            return None\n \n        if key > root.val:\n            root.right = self.deleteNode(root.right, key)\n        elif key &lt; root.val:\n            root.left = self.deleteNode(root.left, key)\n        else:\n            if not (root.left or root.right):\n                root = None\n            elif root.right:\n                root.val = self.successor(root)\n                root.right = self.deleteNode(root.right, root.val)\n            else:\n                root.val = self.predecessor(root)\n                root.left = self.deleteNode(root.left, root.val)\n \n        return root<\/pre>\n\n\n\n<p><strong>Time Complexity:<\/strong> O(logN), where N is the number of nodes.<br><strong>Space Complexity:<\/strong> O(H), for recursion stack, where H is the height of the BST.<\/p>\n\n\n\n<h2 id=\"faqs\">FAQs<\/h2>\n\n\n\n<h3 id=\"q1-why-is-the-time-complexity-logn\"><span id=\"q-1-why-is-the-time-complexity-logn\">Q.1: Why is the time complexity log(N)?<\/span><\/h3>\n\n\n\n<p>Ans. Since the given tree is a BST, we need to traverse the right subtree or left subtree at any given point. Hence, the time complexity is log(N).<\/p>\n\n\n\n<h3 id=\"q2-what-is-the-most-efficient-approach-to-solving-this-problem\"><span id=\"q-2-what-is-the-most-efficient-approach-to-solving-this-problem\">Q.2: What is the most efficient approach to solving this problem?<\/span><\/h3>\n\n\n\n<p>Ans. The recursive approach is the most efficient approach to solving the problem. The time complexity is O(logN) and the space complexity is O(H).<\/p>\n","protected":false},"excerpt":{"rendered":"Problem Statement Given a binary search tree and a key value. The task is to delete the given&hellip;\n","protected":false},"author":5,"featured_media":5106,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_daextam_enable_autolinks":"1","csco_singular_sidebar":"","csco_page_header_type":"","csco_appearance_grid":"","csco_page_load_nextpost":"","csco_post_video_location":[],"csco_post_video_location_hash":"","csco_post_video_url":"","csco_post_video_bg_start_time":0,"csco_post_video_bg_end_time":0},"categories":[145],"tags":[678],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4857"}],"collection":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/comments?post=4857"}],"version-history":[{"count":8,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4857\/revisions"}],"predecessor-version":[{"id":20691,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/4857\/revisions\/20691"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/5106"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=4857"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=4857"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=4857"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}