{"id":27231,"date":"2018-01-05T21:48:48","date_gmt":"2018-01-05T16:18:48","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27231"},"modified":"2018-01-05T21:48:48","modified_gmt":"2018-01-05T16:18:48","slug":"c-program-lowest-common-ancestor-binary-search-tree","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-program-lowest-common-ancestor-binary-search-tree\/","title":{"rendered":"C Program Lowest Common Ancestor in a Binary Search Tree"},"content":{"rendered":"<p>Given values of two nodes in a Binary Search Tree, write a c program to find the <strong>L<\/strong>owest <strong>C<\/strong>ommon <strong>A<\/strong>ncestor (LCA). You may assume that both the values exist in the tree.<span id=\"more-1029\"><\/span><\/p>\n<p>The function prototype should be as follows:<\/p>\n<pre> struct node *lca(node* root, int n1, int n2)\r\n n1 and n2 are two given values in the tree with given root.<\/pre>\n<p>For example, consider the BST in diagram, LCA of 10 and 14 is 12 and LCA of 8 and 14 is 8.<\/p>\n<p><strong>Following is definition of LCA from Wikipedia:<\/strong><br \/>\nLet T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself).<\/p>\n<p>The LCA of n1 and n2 in T is the shared ancestor of n1 and n2 that is located farthest from the root. Computation of lowest common ancestors may be useful, for instance, as part of a procedure for determining the distance between pairs of nodes in a tree: the distance from n1 to n2 can be computed as the distance from the root to n1, plus the distance from the root to n2, minus twice the distance from the root to their lowest common ancestor.<\/p>\n<div id=\"practice\">\n<h4 id=\"ad-typebanner\">[ad type=&#8221;banner&#8221;]<\/h4>\n<\/div>\n<p>If we are given a BST where every node has <strong>parent pointer<\/strong>, then LCA can be easily determined by traversing up using parent pointer and printing the first intersecting node.<\/p>\n<p>We can solve this problem using BST properties. We can <strong>recursively traverse<\/strong> the BST from root. The main idea of the solution is, while traversing from top to bottom, the first node n we encounter with value between n1 and n2, i.e., n1 &lt; n &lt; n2 or same as one of the n1 or n2, is LCA of n1 and n2 (assuming that n1 &lt; n2). So just recursively traverse the BST in, if node\u2019s value is greater than both n1 and n2 then our LCA lies in left side of the node, if it\u2019s is smaller than both n1 and n2, then LCA lies on right side. Otherwise root is LCA (assuming that both n1 and n2 are present in BST)<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C Programming<\/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 recursive C program to find LCA of two nodes n1 and n2.<br\/>#include &lt;stdio.h&gt;<br\/>#include &lt;stdlib.h&gt;<br\/> <br\/>struct node<br\/>{<br\/>    int data;<br\/>    struct node* left, *right;<br\/>};<br\/> <br\/>\/* Function to find LCA of n1 and n2. The function assumes that both<br\/>   n1 and n2 are present in BST *\/<br\/>struct node *lca(struct node* root, int n1, int n2)<br\/>{<br\/>    if (root == NULL) return NULL;<br\/> <br\/>    \/\/ If both n1 and n2 are smaller than root, then LCA lies in left<br\/>    if (root-&gt;data &gt; n1 &amp;&amp; root-&gt;data &gt; n2)<br\/>        return lca(root-&gt;left, n1, n2);<br\/> <br\/>    \/\/ If both n1 and n2 are greater than root, then LCA lies in right<br\/>    if (root-&gt;data &lt; n1 &amp;&amp; root-&gt;data &lt; n2)<br\/>        return lca(root-&gt;right, n1, n2);<br\/> <br\/>    return root;<br\/>}<br\/> <br\/>\/* Helper function that allocates a new node with the given data.*\/<br\/>struct node* newNode(int data)<br\/>{<br\/>    struct node* node = (struct node*)malloc(sizeof(struct node));<br\/>    node-&gt;data  = data;<br\/>    node-&gt;left  = node-&gt;right = NULL;<br\/>    return(node);<br\/>}<br\/> <br\/>\/* Driver program to test lca() *\/<br\/>int main()<br\/>{<br\/>    \/\/ Let us construct the BST shown in the above figure<br\/>    struct node *root        = newNode(20);<br\/>    root-&gt;left               = newNode(8);<br\/>    root-&gt;right              = newNode(22);<br\/>    root-&gt;left-&gt;left         = newNode(4);<br\/>    root-&gt;left-&gt;right        = newNode(12);<br\/>    root-&gt;left-&gt;right-&gt;left  = newNode(10);<br\/>    root-&gt;left-&gt;right-&gt;right = newNode(14);<br\/> <br\/>    int n1 = 10, n2 = 14;<br\/>    struct node *t = lca(root, n1, n2);<br\/>    printf(&quot;LCA of %d and %d is %d \\n&quot;, n1, n2, t-&gt;data);<br\/> <br\/>    n1 = 14, n2 = 8;<br\/>    t = lca(root, n1, n2);<br\/>    printf(&quot;LCA of %d and %d is %d \\n&quot;, n1, n2, t-&gt;data);<br\/> <br\/>    n1 = 10, n2 = 22;<br\/>    t = lca(root, n1, n2);<br\/>    printf(&quot;LCA of %d and %d is %d \\n&quot;, n1, n2, t-&gt;data);<br\/> <br\/>    getchar();<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>LCA of 10 and 14 is 12\r\nLCA of 14 and 8 is 8\r\nLCA of 10 and 22 is 20<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p>Time complexity of above solution is O(h) where h is height of tree. Also, the above solution requires O(h) extra space in function call stack for recursive function calls. We can avoid extra space using <strong>iterative solution<\/strong>.<\/p>\n<div>\n<div id=\"highlighter_323227\" class=\"syntaxhighlighter nogutter cpp\">\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\">\/* Function to find LCA of n1 and n2. The function assumes that both<br\/>   n1 and n2 are present in BST *\/<br\/>struct node *lca(struct node* root, int n1, int n2)<br\/>{<br\/>    while (root != NULL)<br\/>    {<br\/>         \/\/ If both n1 and n2 are smaller than root, then LCA lies in left<br\/>        if (root-&gt;data &gt; n1 &amp;&amp; root-&gt;data &gt; n2)<br\/>           root = root-&gt;left;<br\/> <br\/>        \/\/ If both n1 and n2 are greater than root, then LCA lies in right<br\/>        else if (root-&gt;data &lt; n1 &amp;&amp; root-&gt;data &lt; n2)<br\/>           root = root-&gt;right;<br\/> <br\/>        else break;<br\/>    }<br\/>    return root;<br\/>}<\/code><\/pre> <\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>C Program Lowest Common Ancestor in a Binary Search Tree &#8211; Data Structure &#8211; write a c program to find the Lowest Common Ancestor (LCA).<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[80126,69866,1],"tags":[81212,81239,81209,81210,70052,70270,70265,70321,70277,80557,70268,70296,81218,81219,79501,73332,70280,81213,81216],"class_list":["post-27231","post","type-post","status-publish","format-standard","hentry","category-binary-search-tree","category-c-programming","category-coding","tag-ancestor-tree","tag-ancestry","tag-ancestry-find","tag-ancestry-search","tag-binary-search","tag-binary-search-in-c","tag-binary-search-program-in-c","tag-binary-search-program-in-cpp","tag-binary-search-tree-java","tag-binary-search-tree-with-example","tag-binary-tree","tag-binary-tree-example","tag-binary-tree-interview-questions-java","tag-binary-tree-using-array","tag-data-structure-tutorial-pdf","tag-data-structures-in-c-pdf","tag-search-tree","tag-table-trees","tag-tree-interview-questions-java"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27231","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=27231"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27231\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27231"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27231"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27231"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}