{"id":27098,"date":"2018-01-03T21:25:09","date_gmt":"2018-01-03T15:55:09","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27098"},"modified":"2018-01-03T21:25:09","modified_gmt":"2018-01-03T15:55:09","slug":"optimal-binary-search-tree","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/optimal-binary-search-tree\/","title":{"rendered":"Optimal Binary Search Tree"},"content":{"rendered":"<p>Given a sorted array <em>keys[0.. n-1]<\/em> of search keys and an array <em>freq[0.. n-1]<\/em> of frequency counts, where <em>freq[i]<\/em> is the number of searches to <em>keys[i]<\/em>. Construct a binary search tree of all keys such that the total cost of all the searches is as small as possible.<span id=\"more-28316\"><\/span><\/p>\n<p>Let us first define the cost of a BST. The cost of a BST node is level of that node multiplied by its frequency. Level of root is 1.<\/p>\n<pre><strong>Example 1<\/strong>\r\nInput:  keys[] = {10, 12}, freq[] = {34, 50}\r\nThere can be following two possible BSTs \r\n        10                       12\r\n          \\                     \/ \r\n           12                 10\r\n          I                     II\r\nFrequency of searches of 10 and 12 are 34 and 50 respectively.\r\nThe cost of tree I is 34*1 + 50*2 = 134\r\nThe cost of tree II is 50*1 + 34*2 = 118 \r\n\r\n<strong>Example 2<\/strong>\r\nInput:  keys[] = {10, 12, 20}, freq[] = {34, 8, 50}\r\nThere can be following possible BSTs\r\n    10                12                 20         10              20\r\n      \\             \/    \\              \/             \\            \/\r\n      12          10     20           12               20         10  \r\n        \\                            \/                 \/           \\\r\n         20                        10                12             12  \r\n     I               II             III             IV             V\r\nAmong all possible BSTs, cost of the fifth BST is minimum.  \r\nCost of the fifth BST is 1*50 + 2*34 + 3*8 = 142\r\n<\/pre>\n<ul>\n<li><strong>Optimal Substructure:<\/strong><\/li>\n<\/ul>\n<p>The optimal cost for freq[i..j] can be recursively calculated using following formula.<\/p>\n<p><img decoding=\"async\" class=\"alignleft size-full wp-image-27115\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Optimal-Binary-Search-Tree.png\" alt=\"Optimal Binary Search Tree\" width=\"541\" height=\"43\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Optimal-Binary-Search-Tree.png 541w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Optimal-Binary-Search-Tree-300x24.png 300w\" sizes=\"(max-width: 541px) 100vw, 541px\" \/><br \/>\nWe need to calculate <em><strong>optCost(0, n-1)<\/strong><\/em> to find the result.<\/p>\n<p>The idea of above formula is simple, we one by one try all nodes as root (r varies from i to j in second term). When we make <em>rth<\/em> node as root, we recursively calculate optimal cost from i to r-1 and r+1 to j.<br \/>\nWe add sum of frequencies from i to j (see first term in the above formula), this is added because every search will go through root and one comparison will be done for every search.<\/p>\n[ad type=&#8221;banner&#8221;]\n<ul>\n<li><strong>Overlapping Subproblems<\/strong><\/li>\n<\/ul>\n<p>Following is recursive implementation that simply follows the recursive structure mentioned above.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ A naive recursive implementation of optimal binary search tree problem<br\/>#include &lt;stdio.h&gt;<br\/>#include &lt;limits.h&gt;<br\/> <br\/>\/\/ A utility function to get sum of array elements freq[i] to freq[j]<br\/>int sum(int freq[], int i, int j);<br\/> <br\/>\/\/ A recursive function to calculate cost of optimal binary search tree<br\/>int optCost(int freq[], int i, int j)<br\/>{<br\/>   \/\/ Base cases<br\/>   if (j &lt; i)      \/\/ If there are no elements in this subarray<br\/>     return 0;<br\/>   if (j == i)     \/\/ If there is one element in this subarray<br\/>     return freq[i];<br\/> <br\/>   \/\/ Get sum of freq[i], freq[i+1], ... freq[j]<br\/>   int fsum = sum(freq, i, j);<br\/> <br\/>   \/\/ Initialize minimum value<br\/>   int min = INT_MAX;<br\/> <br\/>   \/\/ One by one consider all elements as root and recursively find cost<br\/>   \/\/ of the BST, compare the cost with min and update min if needed<br\/>   for (int r = i; r &lt;= j; ++r)<br\/>   {<br\/>       int cost = optCost(freq, i, r-1) + optCost(freq, r+1, j);<br\/>       if (cost &lt; min)<br\/>          min = cost;<br\/>   }<br\/> <br\/>   \/\/ Return minimum value<br\/>   return min + fsum;<br\/>}<br\/> <br\/>\/\/ The main function that calculates minimum cost of a Binary Search Tree.<br\/>\/\/ It mainly uses optCost() to find the optimal cost.<br\/>int optimalSearchTree(int keys[], int freq[], int n)<br\/>{<br\/>     \/\/ Here array keys[] is assumed to be sorted in increasing order.<br\/>     \/\/ If keys[] is not sorted, then add code to sort keys, and rearrange<br\/>     \/\/ freq[] accordingly.<br\/>     return optCost(freq, 0, n-1);<br\/>}<br\/> <br\/>\/\/ A utility function to get sum of array elements freq[i] to freq[j]<br\/>int sum(int freq[], int i, int j)<br\/>{<br\/>    int s = 0;<br\/>    for (int k = i; k &lt;=j; k++)<br\/>       s += freq[k];<br\/>    return s;<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    int keys[] = {10, 12, 20};<br\/>    int freq[] = {34, 8, 50};<br\/>    int n = sizeof(keys)\/sizeof(keys[0]);<br\/>    printf(&quot;Cost of Optimal BST is %d &quot;, optimalSearchTree(keys, freq, n));<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output :<\/strong><\/p>\n<pre>Cost of Optimal BST is 142<\/pre>\n<p>Time complexity of the above naive recursive approach is exponential. It should be noted that the above function computes the same subproblems again and again. We can see many subproblems being repeated in the following recursion tree for freq[1..4].<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"size-full wp-image-27124 aligncenter\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Optimal-binary-tree.png\" alt=\"Optimal binary tree\" width=\"656\" height=\"265\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Optimal-binary-tree.png 656w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Optimal-binary-tree-300x121.png 300w\" sizes=\"(max-width: 656px) 100vw, 656px\" \/><\/p>\n<p>Since same suproblems are called again, this problem has Overlapping Subprolems property. So optimal BST problem has both properties of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array cost[][] in bottom up manner.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Dynamic Programming Solution<\/strong><br \/>\nFollowing is C\/C++ implementation for optimal BST problem using Dynamic Programming. We use an auxiliary array cost[n][n] to store the solutions of subproblems. cost[0][n-1] will hold the final result. The challenge in implementation is, all diagonal values must be filled first, then the values which lie on the line just above the diagonal. In other words, we must first fill all cost[i][i] values, then all cost[i][i+1] values, then all cost[i][i+2] values. So how to fill the 2D array in such manner&gt; The idea used in the implementation is same as Matrix Chain Multiplication problem, we use a variable \u2018L\u2019 for chain length and increment \u2018L\u2019, one by one. We calculate column number \u2018j\u2019 using the values of \u2018i\u2019 and \u2018L\u2019.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ Dynamic Programming code for Optimal Binary Search Tree Problem<br\/>#include &lt;stdio.h&gt;<br\/>#include &lt;limits.h&gt;<br\/> <br\/>\/\/ A utility function to get sum of array elements freq[i] to freq[j]<br\/>int sum(int freq[], int i, int j);<br\/> <br\/>\/* A Dynamic Programming based function that calculates minimum cost of<br\/>   a Binary Search Tree. *\/<br\/>int optimalSearchTree(int keys[], int freq[], int n)<br\/>{<br\/>    \/* Create an auxiliary 2D matrix to store results of subproblems *\/<br\/>    int cost[n][n];<br\/> <br\/>    \/* cost[i][j] = Optimal cost of binary search tree that can be<br\/>       formed from keys[i] to keys[j].<br\/>       cost[0][n-1] will store the resultant cost *\/<br\/> <br\/>    \/\/ For a single key, cost is equal to frequency of the key<br\/>    for (int i = 0; i &lt; n; i++)<br\/>        cost[i][i] = freq[i];<br\/> <br\/>    \/\/ Now we need to consider chains of length 2, 3, ... .<br\/>    \/\/ L is chain length.<br\/>    for (int L=2; L&lt;=n; L++)<br\/>    {<br\/>        \/\/ i is row number in cost[][]<br\/>        for (int i=0; i&lt;=n-L+1; i++)<br\/>        {<br\/>            \/\/ Get column number j from row number i and chain length L<br\/>            int j = i+L-1;<br\/>            cost[i][j] = INT_MAX;<br\/> <br\/>            \/\/ Try making all keys in interval keys[i..j] as root<br\/>            for (int r=i; r&lt;=j; r++)<br\/>            {<br\/>               \/\/ c = cost when keys[r] becomes root of this subtree<br\/>               int c = ((r &gt; i)? cost[i][r-1]:0) + <br\/>                       ((r &lt; j)? cost[r+1][j]:0) + <br\/>                       sum(freq, i, j);<br\/>               if (c &lt; cost[i][j])<br\/>                  cost[i][j] = c;<br\/>            }<br\/>        }<br\/>    }<br\/>    return cost[0][n-1];<br\/>}<br\/> <br\/>\/\/ A utility function to get sum of array elements freq[i] to freq[j]<br\/>int sum(int freq[], int i, int j)<br\/>{<br\/>    int s = 0;<br\/>    for (int k = i; k &lt;=j; k++)<br\/>       s += freq[k];<br\/>    return s;<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    int keys[] = {10, 12, 20};<br\/>    int freq[] = {34, 8, 50};<br\/>    int n = sizeof(keys)\/sizeof(keys[0]);<br\/>    printf(&quot;Cost of Optimal BST is %d &quot;, optimalSearchTree(keys, freq, n));<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output :<\/strong><\/p>\n<pre>Cost of Optimal BST is 142<\/pre>\n<p><strong>Notes<\/strong><\/p>\n<ul>\n<li>The time complexity of the above solution is O(n^4). The time complexity can be easily reduced to O(n^3) by pre-calculating sum of frequencies instead of calling sum() again and again.<\/li>\n<li>In the above solutions, we have computed optimal cost only. The solutions can be easily modified to store the structure of BSTs also. We can create another auxiliary array of size n to store the structure of tree. All we need to do is, store the chosen \u2018r\u2019 in the innermost loop.<\/li>\n<\/ul>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Optimal Binary Search Tree &#8211; Dynamic Programming Given a sorted array keys[0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts,<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[82509,70145],"tags":[80836,80831,80832,80835,80841,80828,80824,80838,80839,72852],"class_list":["post-27098","post","type-post","status-publish","format-standard","hentry","category-binary-search-tree-2","category-dynamic-programming","tag-optimal-binary-search-tree-algorithm-using-dynamic-programming","tag-optimal-binary-search-tree-tutorial-point","tag-optimal-binary-search-tree-using-dynamic-programming","tag-optimal-binary-search-tree-using-dynamic-programming-algorithm","tag-optimal-binary-search-tree-using-dynamic-programming-ppt","tag-optimal-binary-search-tree-youtube","tag-optimal-binary-search-trees","tag-optimal-binary-search-trees-using-dynamic-programming","tag-optimal-binary-tree-dynamic-programming","tag-problems-on-dynamic-programming"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27098","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27098"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27098\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27098"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27098"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27098"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}