{"id":2601,"date":"2024-03-17T13:00:00","date_gmt":"2024-03-17T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=2601"},"modified":"2024-03-21T08:00:11","modified_gmt":"2024-03-21T08:00:11","slug":"balance-binary-search-tree","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/balance-binary-search-tree\/","title":{"rendered":"Balance A Binary Search Tree ( C++, Java, Python)"},"content":{"rendered":"\n<p>Binary Search Tree is the most important topic from the interview perspective. It helps you to find the value in the tree in Log(n) time complexity, unlike the normal tree. In this article, we will try the leetcode problem on how to Balance a Binary Search Tree.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Balance a Binary Search Tree problem<\/strong><\/h2>\n\n\n\n<p><strong>In the Balance BST problem, we have given a binary search tree. We have to create another binary search tree that is a balanced version of the given tree. A balanced BST is a BST in which the absolute difference between the left height &#8211; right height\u00a0 &lt;= 1. There may be more than one answer you can return any of them.\u00a0<\/strong><\/p>\n\n\n\n<p>Let\u2019s understand this with an example:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/docsz\/AD_4nXceECkF8mf6L_MvOwYnQ_8KcWtDkMy_jIKuACjOffPwtLevXew0ORK7fptUj9b7qoclPW3HkzqljyqjjCLjAbYaUCRjhueFPn4m07EcH2qz0UUBg4pDdMul02PleIhsmUKmtORCgPMRdGC6aoz2vg?key=C9xSr298rDdsLNt6AmMsrA\" alt=\"Given BST\"\/><\/figure>\n\n\n\n<p>Left and right height of the root node.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/docsz\/AD_4nXddvMv7lpmWUkm0QN0b5hGmBhsDQoDSbos9K6WyAQ3Mfe1_BPtvy5kibncB71BArRdraLndLr44ly83rhDy-9LavLBIw_3QNVgNBnn1VOheF-rlvDUfD_l-A4uLRtKq_WFdJgpHiLVQgCpeZO1MRQ?key=C9xSr298rDdsLNt6AmMsrA\" alt=\"Left and right height of root.\"\/><\/figure>\n\n\n\n<p>The Balanced BST of the given tree looks like<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/docsz\/AD_4nXcOD4PFacrDAmfyYPv4EsRGFhbU1cJmV3VSZ7Dsi74IcN13emmQJBpw3K_AFeufNZN3-DN2fp04-PSwgh_3REnPHVNdrpq5k-Nvlyf0pEcFT0wwhqohqJv4JrORR2JyhF44tDqRy1IP1ScHKrcvNg?key=C9xSr298rDdsLNt6AmMsrA\" alt=\"Balanced BST\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>An In-order Traversal Approach<\/strong><\/h2>\n\n\n\n<p>In this approach, we will find the <a href=\"https:\/\/favtutor.com\/blogs\/inorder-successor-bst\">in-order traversal<\/a> of the given BST. After finding the inorder traversal we will create a function that takes the middle element of the inorder traversal and inorder array. <\/p>\n\n\n\n<p>After that, we will call the left side of the middle value to create the left subtree and the right side of the middle value to create the right subtree.<\/p>\n\n\n\n<p>Let\u2019s examine the approach step by step:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First, create a vector or an array that will store the in-order traversal of the given BST.<\/li>\n\n\n\n<li>Now create a function name inorder_traversal. Pass the root and the vector into that function.<\/li>\n\n\n\n<li>Call the same function for the left subtree. Then store the value of the current node in the vector. And call the function for the right subtree.<\/li>\n\n\n\n<li>Once we get the inorder traversal call the BST function. Pass the vector generated through the in-order function. Pass starting index i.e. 0 and ending index i.e. size of the array.<\/li>\n\n\n\n<li>Find the middle of the starting and ending index. Call the BST function, passing the left part of the middle value to get the left subtree. Call the BST function, passing the right part of the middle value to get the right subtree.<\/li>\n<\/ol>\n\n\n\n<p>The below example shows the inorder traversal of the BST.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/docsz\/AD_4nXcDc_n5AqtgCgVBbX0_5Vs0y2FxZLocltBttMgGRMby8Ck-KXbpWFFh8-mLhR5r_7F6NiiD2c-mewMknAcKJG9Ti6OglUll9gzAjCHz3HFh_DkSBQU0OSRQNvAtVofcBP2a7A5JzWJQ1Q71QE9VEWU?key=C9xSr298rDdsLNt6AmMsrA\" alt=\"In-order array of BST\"\/><\/figure>\n\n\n\n<p>Let\u2019s examine the code for the above process.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Here is the C++ program to balance a binary search tree:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include&lt;bits\/stdc++.h&gt;\n\nusing namespace std;\n\n\u00a0\u00a0\u00a0\u00a0class TreeNode{\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0public:\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0int data;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0TreeNode* left;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0TreeNode* right;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0TreeNode(int x){\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0data = x;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0left = NULL;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0right = NULL;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\n\n\u00a0\u00a0\u00a0\u00a0};\n\n\u00a0\u00a0\u00a0\u00a0void inorder_traversal(TreeNode* root, vector&lt;TreeNode*&gt;&amp; v){\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if(root == NULL) return;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0inorder_traversal(root-&gt;left, v);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0v.push_back(root);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0inorder_traversal(root-&gt;right, v);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return;\n\n\u00a0\u00a0\u00a0\u00a0}\n\n\u00a0\u00a0\u00a0\u00a0TreeNode* BST(int start, int end, vector&lt;TreeNode*&gt;&amp; v) {\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if (start &gt; end) return NULL;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0int mid = (start + end) \/ 2;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0TreeNode* root = v[mid];\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0root-&gt;left = BST(start, mid - 1, v);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0root-&gt;right = BST(mid + 1, end, v);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return root;\n\n\u00a0\u00a0\u00a0\u00a0}\n\n\u00a0\u00a0\u00a0\u00a0void print_BST(TreeNode* root){\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if(root == NULL) return;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0print_BST(root-&gt;left);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0cout&lt;&lt;root-&gt;data&lt;&lt;&quot; &quot;;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0print_BST(root-&gt;right);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return;\n\n\u00a0\u00a0\u00a0\u00a0}\n\n\u00a0\u00a0\u00a0\u00a0int main(){\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0TreeNode* root = new TreeNode(5);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0root-&gt;left = new TreeNode(4);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0root-&gt;left-&gt;left = new TreeNode(3);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0root-&gt;left-&gt;left-&gt;left = new TreeNode(2);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0root-&gt;left-&gt;left-&gt;left-&gt;left = new TreeNode(1);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0vector&lt;TreeNode*&gt;v;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0inorder_traversal(root, v);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0int n = v.size();\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0TreeNode* new_root = BST(0, n-1, v);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\/\/ in-order traverse of balanced BST\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0cout&lt;&lt;&quot;inorder traversal of new BST is &quot;;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0print_BST(new_root);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return 0;\n\n\u00a0\u00a0\u00a0\u00a0}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>Here is the Java program to balance a binary search tree:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">import java.util.*;\n\nclass TreeNode {\n    int data;\n    TreeNode left, right;\n\n    TreeNode(int x) {\n        data = x;\n        left = null;\n        right = null;\n    }\n}\n\npublic class Main {\n    static void inorderTraversal(TreeNode root, ArrayList&lt;TreeNode&gt; v) {\n        if (root == null)\n            return;\n        inorderTraversal(root.left, v);\n        v.add(root);\n        inorderTraversal(root.right, v);\n    }\n\n    static TreeNode BST(int start, int end, ArrayList&lt;TreeNode&gt; v) {\n        if (start &gt; end)\n            return null;\n        int mid = (start + end) \/ 2;\n        TreeNode root = v.get(mid);\n        root.left = BST(start, mid - 1, v);\n        root.right = BST(mid + 1, end, v);\n        return root;\n    }\n\n    static void printBST(TreeNode root) {\n        if (root == null)\n            return;\n        printBST(root.left);\n        System.out.print(root.data + &quot; &quot;);\n        printBST(root.right);\n    }\n\n    public static void main(String[] args) {\n        TreeNode root = new TreeNode(5);\n        root.left = new TreeNode(4);\n        root.left.left = new TreeNode(3);\n        root.left.left.left = new TreeNode(2);\n        root.left.left.left.left = new TreeNode(1);\n\n        ArrayList&lt;TreeNode&gt; v = new ArrayList&lt;&gt;();\n        inorderTraversal(root, v);\n        int n = v.size();\n        TreeNode newRoot = BST(0, n - 1, v);\n\n        \/\/ Inorder traversal of balanced BST\n        System.out.print(&quot;Inorder traversal of new BST is &quot;);\n        printBST(newRoot);\n    }\n}\n<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>We can implement it in Python also:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">class TreeNode:\n\n\u00a0\u00a0\u00a0\u00a0def __init__(self, x):\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0self.data = x\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0self.left = None\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0self.right = None\n\ndef inorder_traversal(root, v):\n\n\u00a0\u00a0\u00a0\u00a0if root is None:\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return\n\n\u00a0\u00a0\u00a0\u00a0inorder_traversal(root.left, v)\n\n\u00a0\u00a0\u00a0\u00a0v.append(root)\n\n\u00a0\u00a0\u00a0\u00a0inorder_traversal(root.right, v)\n\ndef BST(start, end, v):\n\n\u00a0\u00a0\u00a0\u00a0if start &gt; end:\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return None\n\n\u00a0\u00a0\u00a0\u00a0mid = (start + end) \/\/ 2\n\n\u00a0\u00a0\u00a0\u00a0root = v[mid]\n\n\u00a0\u00a0\u00a0\u00a0root.left = BST(start, mid - 1, v)\n\n\u00a0\u00a0\u00a0\u00a0root.right = BST(mid + 1, end, v)\n\n\u00a0\u00a0\u00a0\u00a0return root\n\ndef print_BST(root):\n\n\u00a0\u00a0\u00a0\u00a0if root is None:\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return\n\n\u00a0\u00a0\u00a0\u00a0print_BST(root.left)\n\n\u00a0\u00a0\u00a0\u00a0print(root.data, end=&quot; &quot;)\n\n\u00a0\u00a0\u00a0\u00a0print_BST(root.right)\n\nif __name__ == &quot;__main__&quot;:\n\n\u00a0\u00a0\u00a0\u00a0root = TreeNode(5)\n\n\u00a0\u00a0\u00a0\u00a0root.left = TreeNode(4)\n\n\u00a0\u00a0\u00a0\u00a0root.left.left = TreeNode(3)\n\n\u00a0\u00a0\u00a0\u00a0root.left.left.left = TreeNode(2)\n\n\u00a0\u00a0\u00a0\u00a0root.left.left.left.left = TreeNode(1)\n\n\u00a0\u00a0\u00a0\u00a0v = []\n\n\u00a0\u00a0\u00a0\u00a0inorder_traversal(root, v)\n\n\u00a0\u00a0\u00a0\u00a0n = len(v)\n\n\u00a0\u00a0\u00a0\u00a0new_root = BST(0, n - 1, v)\n\n\u00a0\u00a0\u00a0\u00a0# In inorder to traverse of balanced BST\n\n\u00a0\u00a0\u00a0\u00a0print(&quot;inorder traversal of new BST is &quot;, end=&quot;&quot;)\n\n\u00a0\u00a0\u00a0\u00a0print_BST(new_root)<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong>:&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-e0497418b20e8ce4e38b835da31eeaf9\" style=\"background-color:#fedcba\"><code>inorder traversal of new BST is 1 2 3 4 5&nbsp;<\/code><\/pre>\n\n\n\n<p>The time complexity to balance a binary search tree using in-order traversal is O(n), Where n is the total number of nodes present in the given BST. As we are calling two functions one is inorder_traversal and another is BST both time complexity is O(n).<\/p>\n\n\n\n<p>The space complexity is also O(n). We are storing the values of nodes in the array.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we solved the Blaance Binary Search Tree problem from <a href=\"https:\/\/leetcode.com\/problems\/balance-a-binary-search-tree\/description\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">leetcode<\/a>. Remember that if BST is not balanced then the searching operation may take O(n) time. But by balancing the BST time and complexity will reduced to O(log(n)). <\/p>\n","protected":false},"excerpt":{"rendered":"<p>We will solve the leetcode problem to Balance a Binary Search Tree using in-order traversal approach and implement it in C++, Java, and Python.<\/p>\n","protected":false},"author":14,"featured_media":2615,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-2601","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2601","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=2601"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2601\/revisions"}],"predecessor-version":[{"id":2754,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2601\/revisions\/2754"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/2615"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=2601"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=2601"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=2601"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}