{"id":27236,"date":"2018-01-05T21:50:37","date_gmt":"2018-01-05T16:20:37","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27236"},"modified":"2018-10-31T11:05:42","modified_gmt":"2018-10-31T05:35:42","slug":"python-program-lowest-common-ancestor-binary-search-tree","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-program-lowest-common-ancestor-binary-search-tree\/","title":{"rendered":"Lowest Common Ancestor in a Binary Search Tree"},"content":{"rendered":"<p><span style=\"color: #333399;\"><strong>Python Program Lowest Common Ancestor in Binary Search Tree:<\/strong><\/span><\/p>\n<p>Given values of two nodes in a <a href=\"https:\/\/www.wikitechy.com\/technology\/python-program-inorder-successor-binary-search-tree\/\" target=\"_blank\" rel=\"noopener\">Binary Search Tree<\/a>, write a <a href=\"https:\/\/www.wikitechy.com\/tutorials\/python\/python-program-to-reverse-a-number\" target=\"_blank\" rel=\"noopener\">Python<\/a> program to find the <strong>L<\/strong>owest <strong>C<\/strong>ommon <strong>A<\/strong>ncestor (<strong>LCA<\/strong>). 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.\r\n<img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-31754\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2018\/01\/bst-tree.png\" alt=\" binary search trees\" width=\"303\" height=\"255\" \/><\/pre>\n<p>For example, consider the <a href=\"https:\/\/www.wikitechy.com\/technology\/java-program-check-binary-tree-bst-not\/\" target=\"_blank\" rel=\"noopener\">BST<\/a> in diagram, LCA of 10 and 14 is 12 and LCA of 8 and 14 is 8.<\/p>\n<h3 id=\"following-is-definition-of-lca-from-wikipedia\"><span style=\"color: #333300;\"><strong>Following is definition of LCA from Wikipedia:<\/strong><\/span><\/h3>\n<p>Let T be a rooted tree. The <a href=\"https:\/\/www.wikitechy.com\/technology\/c-program-lowest-common-ancestor-binary-search-tree\/\" target=\"_blank\" rel=\"noopener\">lowest common ancestor<\/a> 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. (Source Wiki)<\/p>\n<div id=\"practice\"><\/div>\n[ad type=&#8221;banner&#8221;]\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<h3 id=\"implementation-of-python-program\"><span style=\"color: #000080;\">Implementation of Python Program:<\/span><\/h3>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Python Programming<\/span> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># A recursive python program to find LCA of two nodes<br\/># n1 and n2<br\/> <br\/># A Binary tree node<br\/>class Node:<br\/> <br\/>    # Constructor to create a new node<br\/>    def __init__(self, data):<br\/>        self.data = data<br\/>        self.left = None<br\/>        self.right = None<br\/> <br\/># Function to find LCA of n1 and n2. The function assumes<br\/># that both n1 and n2 are present in BST<br\/>def lca(root, n1, n2):<br\/>     <br\/>    # Base Case<br\/>    if root is None:<br\/>        return None<br\/> <br\/>    # If both n1 and n2 are smaller than root, then LCA<br\/>    # lies in left<br\/>    if(root.data &gt; n1 and root.data &gt; n2):<br\/>        return lca(root.left, n1, n2)<br\/> <br\/>    # If both n1 and n2 are greater than root, then LCA<br\/>    # lies in right <br\/>    if(root.data &lt; n1 and root.data &lt; n2):<br\/>        return lca(root.right, n1, n2)<br\/> <br\/>    return root<br\/> <br\/># Driver program to test above function<br\/> <br\/># Let us construct the BST shown in the figure<br\/>root = Node(20)<br\/>root.left = Node(8)<br\/>root.right = Node(22)<br\/>root.left.left = Node(4)<br\/>root.left.right = Node(12)<br\/>root.left.right.left = Node(10)<br\/>root.left.right.right = Node(14)<br\/> <br\/>n1 = 10 ; n2 = 14<br\/>t = lca(root, n1, n2)<br\/>print &quot;LCA of %d and %d is %d&quot; %(n1, n2, t.data)<br\/> <br\/>n1 = 14 ; n2 = 8<br\/>t = lca(root, n1, n2)<br\/>print &quot;LCA of %d and %d is %d&quot; %(n1, n2 , t.data)<br\/> <br\/>n1 = 10 ; n2 = 22<br\/>t = lca(root, n1, n2)<br\/>print &quot;LCA of %d and %d is %d&quot; %(n1, n2, t.data)<br\/> <br\/># This code is contributed by Nikhil Kumar Singh(nickzuck_007)<\/code><\/pre> <\/div>\n<h3 id=\"output\"><span style=\"color: #003300;\"><strong>Output:<\/strong><\/span><\/h3>\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<p><span style=\"color: #008080;\"><strong>Time complexity<\/strong><\/span> of above solution is <strong>O(h)<\/strong> where h is height of tree.<\/p>\n<p>Also, the above solution requires O(h) extra space in function call stack for <a href=\"https:\/\/www.wikitechy.com\/technology\/c-algorithm-write-recursive-function-print-reverse-linked-list\/\" target=\"_blank\" rel=\"noopener\">recursive function<\/a> calls. We can avoid extra space using <strong>iterative solution<\/strong>.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Python Program &#8211; 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,1,4148],"tags":[81200,81199,81203,81204,81202,81201,81238,81207,79469,81232,81226,81237,81224,70280,81235,81213,81234,81222],"class_list":["post-27236","post","type-post","status-publish","format-standard","hentry","category-binary-search-tree","category-coding","category-python","tag-lowest-common-ancestor-binary-search-tree","tag-lowest-common-ancestor-binary-tree","tag-lowest-common-ancestor-binary-tree-parent-pointer","tag-lowest-common-ancestor-n-ary-tree","tag-lowest-common-ancestor-of-a-binary-tree-java","tag-lowest-common-ancestor-of-a-binary-tree-leetcode","tag-lowest-common-ancestor-of-a-binary-tree-python","tag-node-interview-questions","tag-on","tag-questions-on-binary-search-tree","tag-questions-on-binary-tree","tag-range-minimum-query","tag-range-tree","tag-search-tree","tag-sparse-table","tag-table-trees","tag-tree-interview-questions","tag-tree-interview-questions-and-answers"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27236","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=27236"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27236\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27236"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27236"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27236"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}