|
| 1 | +# Lowest Common Ancestor in a Binary Tree |
| 2 | +## Medium |
| 3 | +<div class="problems_problem_content__Xm_eO"><p><span style="font-size:18px"><span style="font-family:arial,helvetica,sans-serif">Given a Binary Tree with all <strong>unique</strong> values and two nodes value, <strong>n1</strong> and <strong>n2</strong>. The task is to find the<strong> lowest common ancestor</strong> of the given two nodes. We may assume that either both n1 and n2 are present in the tree or none of them are present. </span></span></p> |
| 4 | + |
| 5 | +<p><span style="font-size:18px">LCA: It is the first common ancestor of both the nodes n1 and n2 from bottom of tree.</span></p> |
| 6 | + |
| 7 | +<p><span style="font-size:18px"><strong>Example 1:</strong></span></p> |
| 8 | + |
| 9 | +<pre><span style="font-size:18px"><strong>Input: |
| 10 | +</strong>n1 = 2 , n2 = 3 |
| 11 | + 1 |
| 12 | + / \ |
| 13 | + 2 3 |
| 14 | +<strong>Output: </strong><span style="font-family:arial,helvetica,sans-serif">1 |
| 15 | +</span><strong>Explanation: |
| 16 | +</strong></span><span style="font-size:18px">LCA of 2 and 3 is 1.</span></pre> |
| 17 | + |
| 18 | +<p><span style="font-size:18px"><strong>Example 2:</strong></span></p> |
| 19 | + |
| 20 | +<pre><span style="font-size:18px"><strong>Input: |
| 21 | +</strong>n1 = 3 , n2 = 4 |
| 22 | + 5 |
| 23 | + / |
| 24 | + 2 |
| 25 | + / \ |
| 26 | + 3 4 |
| 27 | +<strong>Output: </strong><span style="font-family:arial,helvetica,sans-serif">2 |
| 28 | +</span><strong>Explanation: |
| 29 | +</strong>LCA of 3 and 4 is 2.<strong> </strong></span></pre> |
| 30 | + |
| 31 | +<p><span style="font-size:18px"><span style="font-family:arial,helvetica,sans-serif"><strong>Your Task:</strong><br> |
| 32 | +You don't have to read, input, or print anything. Your task is to complete the function <strong>lca() </strong>that takes nodes, <strong>n1, and n2</strong> as parameters and returns the <strong>LCA </strong>node as output. </span></span></p> |
| 33 | + |
| 34 | +<p><span style="font-size:18px"><span style="font-family:arial,helvetica,sans-serif"><strong>Expected Time Complexity:</strong>O(N).<br> |
| 35 | +<strong>Expected Auxiliary Space:</strong>O(Height of Tree).</span></span></p> |
| 36 | + |
| 37 | +<p><span style="font-size:18px"><span style="font-family:arial,helvetica,sans-serif"><strong>Constraints:</strong><br> |
| 38 | +1 ≤ Number of nodes ≤ 10<sup>5</sup><br> |
| 39 | +1 ≤ Data of a node ≤ 10<sup>5</sup></span></span></p> |
| 40 | +</div> |
0 commit comments