{"id":27375,"date":"2018-02-02T20:54:39","date_gmt":"2018-02-02T15:24:39","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27375"},"modified":"2018-02-02T20:54:39","modified_gmt":"2018-02-02T15:24:39","slug":"c-program-kth-smallest-element-bst-using-o1-extra-space","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-program-kth-smallest-element-bst-using-o1-extra-space\/","title":{"rendered":"C++ Program-K\u2019th smallest element in BST using O(1) Extra Space"},"content":{"rendered":"<p>Given a Binary Search Tree (BST) and a positive integer k, find the k\u2019th smallest element in the Binary Search Tree.<span id=\"more-135105\"><\/span><\/p>\n<p>For example, in the following BST, if k = 3, then output should be 10, and if k = 5, then output should be 14.<\/p>\n<p>We have discussed two methods in <a href=\"http:\/\/www.geeksforgeeks.org\/find-k-th-smallest-element-in-bst-order-statistics-in-bst\/\" target=\"_blank\" rel=\"noopener\">this <\/a>post and one method in <a href=\"http:\/\/www.geeksforgeeks.org\/kth-largest-element-in-bst-when-modification-to-bst-is-not-allowed\/\" target=\"_blank\" rel=\"noopener\">this <\/a>post. All of the previous methods require extra space. How to find the k\u2019th largest element without extra space?<\/p>\n<p><strong>We strongly recommend to minimize your browser and try this yourself first.<\/strong><strong>Implementation<\/strong><\/p>\n<p>The idea is to use <a href=\"http:\/\/www.geeksforgeeks.org\/inorder-tree-traversal-without-recursion-and-without-stack\/\" target=\"_blank\" rel=\"noopener\">Morris Traversal<\/a>. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. See <a href=\"http:\/\/www.geeksforgeeks.org\/inorder-tree-traversal-without-recursion-and-without-stack\/\" target=\"_blank\" rel=\"noopener\">this <\/a>for more details.<\/p>\n<p>Below is C++ implementation of the idea.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C++ Programming<\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ C++ program to find k&#039;th largest element in BST<br\/>#include&lt;iostream&gt;<br\/>#include&lt;climits&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ A BST node<br\/>struct Node<br\/>{<br\/>    int key;<br\/>    Node *left, *right;<br\/>};<br\/> <br\/>\/\/ A function to find<br\/>int KSmallestUsingMorris(Node *root, int k)<br\/>{<br\/>    \/\/ Count to iterate over elements till we<br\/>    \/\/ get the kth smallest number<br\/>    int count = 0;<br\/> <br\/>    int ksmall = INT_MIN; \/\/ store the Kth smallest<br\/>    Node *curr = root; \/\/ to store the current node<br\/> <br\/>    while (curr != NULL)<br\/>    {<br\/>        \/\/ Like Morris traversal if current does<br\/>        \/\/ not have left child rather than printing<br\/>        \/\/ as we did in inorder, we will just<br\/>        \/\/ increment the count as the number will<br\/>        \/\/ be in an increasing order<br\/>        if (curr-&gt;left == NULL)<br\/>        {<br\/>            count++;<br\/> <br\/>            \/\/ if count is equal to K then we found the<br\/>            \/\/ kth smallest, so store it in ksmall<br\/>            if (count==k)<br\/>                ksmall = curr-&gt;key;<br\/> <br\/>            \/\/ go to current&#039;s right child<br\/>            curr = curr-&gt;right;<br\/>        }<br\/>        else<br\/>        {<br\/>            \/\/ we create links to Inorder Successor and<br\/>            \/\/ count using these links<br\/>            Node *pre = curr-&gt;left;<br\/>            while (pre-&gt;right != NULL &amp;&amp; pre-&gt;right != curr)<br\/>                pre = pre-&gt;right;<br\/> <br\/>            \/\/ building links<br\/>            if (pre-&gt;right==NULL)<br\/>            {<br\/>                \/\/link made to Inorder Successor<br\/>                pre-&gt;right = curr;<br\/>                curr = curr-&gt;left;<br\/>            }<br\/> <br\/>            \/\/ While breaking the links in so made temporary<br\/>            \/\/ threaded tree we will check for the K smallest<br\/>            \/\/ condition<br\/>            else<br\/>            {<br\/>                \/\/ Revert the changes made in if part (break link<br\/>                \/\/ from the Inorder Successor)<br\/>                pre-&gt;right = NULL;<br\/> <br\/>                count++;<br\/> <br\/>                \/\/ If count is equal to K then we found<br\/>                \/\/ the kth smallest and so store it in ksmall<br\/>                if (count==k)<br\/>                    ksmall = curr-&gt;key;<br\/> <br\/>                curr = curr-&gt;right;<br\/>            }<br\/>        }<br\/>    }<br\/>    return ksmall; \/\/return the found value<br\/>}<br\/> <br\/>\/\/ A utility function to create a new BST node<br\/>Node *newNode(int item)<br\/>{<br\/>    Node *temp = new Node;<br\/>    temp-&gt;key = item;<br\/>    temp-&gt;left = temp-&gt;right = NULL;<br\/>    return temp;<br\/>}<br\/> <br\/>\/* A utility function to insert a new node with given key in BST *\/<br\/>Node* insert(Node* node, int key)<br\/>{<br\/>    \/* If the tree is empty, return a new node *\/<br\/>    if (node == NULL) return newNode(key);<br\/> <br\/>    \/* Otherwise, recur down the tree *\/<br\/>    if (key &lt; node-&gt;key)<br\/>        node-&gt;left  = insert(node-&gt;left, key);<br\/>    else if (key &gt; node-&gt;key)<br\/>        node-&gt;right = insert(node-&gt;right, key);<br\/> <br\/>    \/* return the (unchanged) node pointer *\/<br\/>    return node;<br\/>}<br\/> <br\/>\/\/ Driver Program to test above functions<br\/>int main()<br\/>{<br\/>    \/* Let us create following BST<br\/>              50<br\/>           \/     \\<br\/>          30      70<br\/>         \/  \\    \/  \\<br\/>       20   40  60   80 *\/<br\/>    Node *root = NULL;<br\/>    root = insert(root, 50);<br\/>    insert(root, 30);<br\/>    insert(root, 20);<br\/>    insert(root, 40);<br\/>    insert(root, 70);<br\/>    insert(root, 60);<br\/>    insert(root, 80);<br\/> <br\/>    for (int k=1; k&lt;=7; k++)<br\/>       cout &lt;&lt; KSmallestUsingMorris(root, k) &lt;&lt; &quot; &quot;;<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Output:<\/strong><\/p>\n<pre>20 30 40 50 60 70 80<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>K\u2019th smallest element in BST using O(1) Extra Space &#8211; Binary Search Tree &#8211; Given a Binary Search Tree (BST) and positive integer k, find the k\u2019th smallest.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[80126,83515],"tags":[81505,81338,81507,81334,81337,81331,81335,81332,81506,81333,81330],"class_list":["post-27375","post","type-post","status-publish","format-standard","hentry","category-binary-search-tree","category-c-programming-3","tag-2-sum-binary-tree","tag-algorithm-to-find-pair-of-numbers-whose-sum-is-equal-to-k","tag-c-program-kth-smallest-element-in-bst-using-o1-extra-space","tag-find-the-second-largest-element-in-a-binary-search-tree","tag-given-an-array-and-a-number-k","tag-kth-largest-element-in-bst-java","tag-kth-smallest-element-in-a-array","tag-kth-smallest-element-in-a-bst-c","tag-kth-smallest-element-in-a-bst-leetcode-c","tag-kth-smallest-element-in-a-bst-recursive","tag-kth-smallest-element-in-bst-java"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27375","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=27375"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27375\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27375"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27375"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27375"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}