Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Lowest Common Ancestor in a Binary Tree
Next article icon

Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)

Last Updated : 04 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a rooted tree, and two nodes are in the tree, find the Lowest common ancestor of both the nodes. The LCA for two nodes u and v is defined as the farthest node from the root that is the ancestor to both u and v. 
Prerequisites: LCA | SET 1
 

lca

Example for the above figure : 

Input : 4 5 Output : 2  Input : 4 7 Output : 1

Converting LCA to RMQ(Range Minimum Query): 
Take an array named E[], which stores the order of dfs traversal i.e. the order in which the nodes are covered during the dfs traversal. For example, 
 

The tree given above has dfs traversal in the order: 1-2-4-2-5-2-1-3. Take another array L[], in which L[i] is the level of node E[i]. And the array H[], which stores the index of the first occurrence of ith node in the array E[]. So, for the above tree,  E[] = {1, 2, 4, 2, 5, 2, 1, 3}  L[] = {1, 2, 3, 2, 3, 2, 1, 2}  H[] = {0, 1, 7, 2, 4} 

Note that the arrays E and L are with one-based indexing but the array H has zero-based indexing.

Now, to find the LCA(4, 3), first, use the array H and find the indices at which 4 and 3 are found in E i.e. H[4] and H[3]. So, the indices come out to be 2 and 7. Now, look at the subarray L[2 : 7], and find the minimum in this subarray which is 1 (at the 6th index), and the corresponding element in the array E i.e. E[6] is the LCA(4, 3).

To understand why this works, take LCA(4, 3) again. The path by which one can reach node 3 from node 4 is the subarray E[2 : 7]. And, if there is a node with the lowest level in this path, then it can simply be claimed to be the LCA(4, 3).

Now, the problem is to find the minimum in the subarray E[H[u]….H[v]] (assuming that H[u] >= H[v]). And, that could be done using a segment tree or sparse table. Below is the code using the segment tree. 

Implementation:

C++




// CPP code to find LCA of given
// two nodes in a tree
#include <bits/stdc++.h>
 
#define sz(x) x.size()
#define pb push_back
#define left 2 * i + 1
#define right 2 * i + 2
using namespace std;
 
const int maxn = 100005;
 
// the graph
vector<vector<int>> g(maxn);
 
// level of each node
int level[maxn];
 
vector<int> e;
vector<int> l;
int h[maxn];
 
// the segment tree
int st[5 * maxn];
 
// adding edges to the graph(tree)
void add_edge(int u, int v) {
  g[u].pb(v);
  g[v].pb(u);
}
 
// assigning level to nodes
void leveling(int src) {
  for (int i = 0; i < sz(g[src]); i++) {
    int des = g[src][i];
    if (!level[des]) {
      level[des] = level[src] + 1;
      leveling(des);
    }
  }
}
 
bool visited[maxn];
 
// storing the dfs traversal
// in the array e
void dfs(int src) {
  e.pb(src);
  visited[src] = 1;
  for (int i = 0; i < sz(g[src]); i++) {
    int des = g[src][i];
    if (!visited[des]) {
      dfs(des);
      e.pb(src);
    }
  }
}
 
// making the array l
void setting_l(int n) {
  for (int i = 0; i < sz(e); i++)
    l.pb(level[e[i]]);
}
 
// making the array h
void setting_h(int n) {
  for (int i = 0; i <= n; i++)
    h[i] = -1;
  for (int i = 0; i < sz(e); i++) {
    // if is already stored
    if (h[e[i]] == -1)
      h[e[i]] = i;
  }
}
 
// Range minimum query to return the index
// of minimum in the subarray L[qs:qe]
int RMQ(int ss, int se, int qs, int qe, int i) {
  if (ss > se)
    return -1;
 
  // out of range
  if (se < qs || qe < ss)
    return -1;
 
  // in the range
  if (qs <= ss && se <= qe)
    return st[i];
 
  int mid = (ss + se) >> 1;
  int st = RMQ(ss, mid, qs, qe, left);
  int en = RMQ(mid + 1, se, qs, qe, right);
 
  if (st != -1 && en != -1) {
    if (l[st] < l[en])
      return st;
    return en;
  } else if (st != -1)
    return st;
  else if (en != -1)
    return en;
}
 
// constructs the segment tree
void SegmentTreeConstruction(int ss, int se, int i) {
  if (ss > se)
    return;
  if (ss == se) // leaf
  {
    st[i] = ss;
    return;
  }
  int mid = (ss + se) >> 1;
 
  SegmentTreeConstruction(ss, mid, left);
  SegmentTreeConstruction(mid + 1, se, right);
 
  if (l[st[left]] < l[st[right]])
    st[i] = st[left];
  else
    st[i] = st[right];
}
 
// Function to get LCA
int LCA(int x, int y) {
  if (h[x] > h[y])
    swap(x, y);
  return e[RMQ(0, sz(l) - 1, h[x], h[y], 0)];
}
 
// Driver code
int main() {
 
  // n=number of nodes in the tree
  // q=number of queries to answer
  int n = 15, q = 5;
 
  // making the tree
  /*
                   1
                 / | \
                2  3  4
                   |   \
                   5    6
                 / |  \
               8   7    9 (right of 5)
                 / | \   | \
               10 11 12 13 14
                      |
                      15
  */
  add_edge(1, 2);
  add_edge(1, 3);
  add_edge(1, 4);
  add_edge(3, 5);
  add_edge(4, 6);
  add_edge(5, 7);
  add_edge(5, 8);
  add_edge(5, 9);
  add_edge(7, 10);
  add_edge(7, 11);
  add_edge(7, 12);
  add_edge(9, 13);
  add_edge(9, 14);
  add_edge(12, 15);
 
  level[1] = 1;
  leveling(1);
 
  dfs(1);
 
  setting_l(n);
 
  setting_h(n);
 
  SegmentTreeConstruction(0, sz(l) - 1, 0);
 
  cout << LCA(10, 15) << endl;
  cout << LCA(11, 14) << endl;
 
  return 0;
}
 
 

Java




// JAVA code to find LCA of given
// two nodes in a tree
import java.util.*;
public class GFG
{
 
  static int maxn = 100005;
  static  int left(int i)
  {
    return  (2 * i + 1);
  }
  static  int right(int i) { return 2 * i + 2;}
 
  // the graph
  static Vector<Integer> []g = new Vector[maxn];
 
  // level of each node
  static int []level = new int[maxn];
  static Vector<Integer> e = new Vector<>();
  static Vector<Integer> l= new Vector<>();
  static int []h = new int[maxn];
 
  // the segment tree
  static int []st = new int[5 * maxn];
 
  // adding edges to the graph(tree)
  static void add_edge(int u, int v)
  {
    g[u].add(v);
    g[v].add(u);
  }
 
  // assigning level to nodes
  static void levelling(int src)
  {
    for (int i = 0; i < (g[src].size()); i++)
    {
      int des = g[src].get(i);
      if (level[des] != 0)
      {
        level[des] = level[src] + 1;
        leveling(des);
      }
    }
  }
 
  static boolean []visited = new boolean[maxn];
 
  // storing the dfs traversal
  // in the array e
  static void dfs(int src)
  {
    e.add(src);
    visited[src] = true;
    for (int i = 0; i < (g[src]).size(); i++)
    {
      int des = g[src].get(i);
      if (!visited[des])
      {
        dfs(des);
        e.add(src);
      }
    }
  }
 
  // making the array l
  static void setting_l(int n)
  {
    for (int i = 0; i < e.size(); i++)
      l.add(level[e.get(i)]);
  }
 
  // making the array h
  static void setting_h(int n)
  {
    for (int i = 0; i <= n; i++)
      h[i] = -1;
    for (int i = 0; i < e.size(); i++)
    {
 
      // if is already stored
      if (h[e.get(i)] == -1)
        h[e.get(i)] = i;
    }
  }
 
  // Range minimum query to return the index
  // of minimum in the subarray L[qs:qe]
  static int RMQ(int ss, int se, int qs, int qe, int i)
  {
    if (ss > se)
      return -1;
 
    // out of range
    if (se < qs || qe < ss)
      return -1;
 
    // in the range
    if (qs <= ss && se <= qe)
      return st[i];
 
    int mid = (ss + se)/2 ;
    int st = RMQ(ss, mid, qs, qe, left(i));
    int en = RMQ(mid + 1, se, qs, qe, right(i));
 
    if (st != -1 && en != -1)
    {
      if (l.get(st) < l.get(en))
        return st;
      return en;
    } else if (st != -1)
      return st-2;
    else if (en != -1)
      return en-1;
    return 0;
  }
 
  // constructs the segment tree
  static void SegmentTreeConstruction(int ss,
                                      int se, int i)
  {
    if (ss > se)
      return;
    if (ss == se) // leaf
    {
      st[i] = ss;
      return;
    }
    int mid = (ss + se) /2;
 
    SegmentTreeConstruction(ss, mid, left(i));
    SegmentTreeConstruction(mid + 1, se, right(i));
    if (l.get(st[left(i)]) < l.get(st[right(i)]))
      st[i] = st[left(i)];
    else
      st[i] = st[right(i)];
  }
 
  // Function to get LCA
  static int LCA(int x, int y)
  {
    if (h[x] > h[y])
    {
      int t = x;
      x = y;
      y = t;
    }
    return e.get(RMQ(0, l.size() - 1, h[x], h[y], 0));
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    // n=number of nodes in the tree
    // q=number of queries to answer
    int n = 15, q = 5;
    for (int i = 0; i < g.length; i++)
      g[i] = new Vector<Integer>();
 
    // making the tree
    /*
                   1
                 / | \
                2  3  4
                   |   \
                   5    6
                 / |  \
               8   7    9 (right of 5)
                 / | \   | \
               10 11 12 13 14
                      |
                      15
  */
    add_edge(1, 2);
    add_edge(1, 3);
    add_edge(1, 4);
    add_edge(3, 5);
    add_edge(4, 6);
    add_edge(5, 7);
    add_edge(5, 8);
    add_edge(5, 9);
    add_edge(7, 10);
    add_edge(7, 11);
    add_edge(7, 12);
    add_edge(9, 13);
    add_edge(9, 14);
    add_edge(12, 15);
    level[1] = 1;
    leveling(1);
    dfs(1);
    setting_l(n);
    setting_h(n);
    SegmentTreeConstruction(0, l.size() - 1, 0);
    System.out.print(LCA(10, 15) +"\n");
    System.out.print(LCA(11, 14) +"\n");
  }
}
 
// This code is contributed by Rajput-Ji
 
 

Python3




# Python code to find LCA of given
# two nodes in a tree
 
maxn = 100005
 
# the graph
g = [[] for i in range(maxn)]
 
# level of each node
level = [0] * maxn
 
e = []
l = []
h = [0] * maxn
 
# the segment tree
st = [0] * (5 * maxn)
 
# adding edges to the graph(tree)
def add_edge(u: int, v: int):
    g[u].append(v)
    g[v].append(u)
 
# assigning level to nodes
def levelling(src: int):
    for i in range(len(g[src])):
        des = g[src][i]
        if not level[des]:
            level[des] = level[src] + 1
            leveling(des)
 
visited = [False] * maxn
 
# storing the dfs traversal
# in the array e
def dfs(src: int):
    e.append(src)
    visited[src] = True
    for i in range(len(g[src])):
        des = g[src][i]
        if not visited[des]:
            dfs(des)
            e.append(src)
 
# making the array l
def setting_l(n: int):
    for i in range(len(e)):
        l.append(level[e[i]])
 
# making the array h
def setting_h(n: int):
    for i in range(n + 1):
        h[i] = -1
    for i in range(len(e)):
 
        # if is already stored
        if h[e[i]] == -1:
            h[e[i]] = i
 
# Range minimum query to return the index
# of minimum in the subarray L[qs:qe]
def RMQ(ss: int, se: int, qs: int, qe: int, i: int) -> int:
    global st
    if ss > se:
        return -1
 
    # out of range
    if se < qs or qe < ss:
        return -1
 
    # in the range
    if qs <= ss and se <= qe:
        return st[i]
 
    mid = (se + ss) >> 1
    stt = RMQ(ss, mid, qs, qe, 2 * i + 1)
    en = RMQ(mid + 1, se, qs, qe, 2 * i + 2)
 
    if stt != -1 and en != -1:
        if l[stt] < l[en]:
            return stt
        return en
    elif stt != -1:
        return stt
    elif en != -1:
        return en
 
# constructs the segment tree
def segmentTreeConstruction(ss: int, se: int, i: int):
    if ss > se:
        return
    if ss == se: # leaf
        st[i] = ss
        return
 
    mid = (ss + se) >> 1
    segmentTreeConstruction(ss, mid, 2 * i + 1)
    segmentTreeConstruction(mid + 1, se, 2 * i + 2)
 
    if l[st[2 * i + 1]] < l[st[2 * i + 2]]:
        st[i] = st[2 * i + 1]
    else:
        st[i] = st[2 * i + 2]
 
# Function to get LCA
def LCA(x: int, y: int) -> int:
    if h[x] > h[y]:
        x, y = y, x
    return e[RMQ(0, len(l) - 1, h[x], h[y], 0)]
 
# Driver Code
if __name__ == "__main__":
 
    # n=number of nodes in the tree
    # q=number of queries to answer
    n = 15
    q = 5
 
    # making the tree
    # /*
    #         1
    #     / | \
    #     2 3 4
    #         | \
    #         5 6
    #     / | \
    #     8 7 9 (right of 5)
    #     / | \ | \
    #     10 11 12 13 14
    #             |
    #             15
    # */
    add_edge(1, 2)
    add_edge(1, 3)
    add_edge(1, 4)
    add_edge(3, 5)
    add_edge(4, 6)
    add_edge(5, 7)
    add_edge(5, 8)
    add_edge(5, 9)
    add_edge(7, 10)
    add_edge(7, 11)
    add_edge(7, 12)
    add_edge(9, 13)
    add_edge(9, 14)
    add_edge(12, 15)
 
    level[1] = 1
    leveling(1)
    dfs(1)
    setting_l(n)
    setting_h(n)
 
    segmentTreeConstruction(0, len(l) - 1, 0)
 
    print(LCA(10, 15))
    print(LCA(11, 14))
 
# This code is contributed by
# sanjeev2552
 
 

C#




// C# code to find LCA of given
// two nodes in a tree
using System;
using System.Collections.Generic;
public class GFG
{
  static int maxn = 100005;
  static  int left(int i)
  {
    return  (2 * i + 1);
  }
  static  int right(int i) { return 2 * i + 2;}
 
  // the graph
  static List<int> []g = new List<int>[maxn];
 
  // level of each node
  static int []level = new int[maxn];
  static List<int> e = new List<int>();
  static List<int> l= new List<int>();
  static int []h = new int[maxn];
 
  // the segment tree
  static int []st;
 
  // adding edges to the graph(tree)
  static void add_edge(int u, int v)
  {
    g[u].Add(v);
    g[v].Add(u);
  }
 
  // assigning level to nodes
  static void leveling(int src)
  {
    for (int i = 0; i < (g[src].Count); i++)
    {
      int des = g[src][i];
      if (level[des] != 0)
      {
        level[des] = level[src] + 1;
        leveling(des);
      }
    }
  }
  static bool []visited = new bool[maxn];
 
  // storing the dfs traversal
  // in the array e
  static void dfs(int src)
  {
    e.Add(src);
    visited[src] = true;
    for (int i = 0; i < (g[src]).Count; i++)
    {
      int des = g[src][i];
      if (!visited[des])
      {
        dfs(des);
        e.Add(src);
      }
    }
  }
 
  // making the array l
  static void setting_l(int n)
  {
    for (int i = 0; i < e.Count; i++)
      l.Add(level[e[i]]);
  }
 
  // making the array h
  static void setting_h(int n)
  {
    for (int i = 0; i <= n; i++)
      h[i] = -1;
    for (int i = 0; i < e.Count; i++)
    {
 
      // if is already stored
      if (h[e[i]] == -1)
        h[e[i]] = i;
    }
  }
 
  // Range minimum query to return the index
  // of minimum in the subarray L[qs:qe]
  static int RMQ(int ss, int se, int qs, int qe, int i)
  {
    if (ss > se)
      return -1;
 
    // out of range
    if (se < qs || qe < ss)
      return -1;
 
    // in the range
    if (qs <= ss && se <= qe)
      return st[i];
 
    int mid = (ss + se)/2 ;
    int sti = RMQ(ss, mid, qs, qe, left(i));
    int en = RMQ(mid + 1, se, qs, qe, right(i));
 
    if (sti != -1 && en != -1)
    {
      if (l[sti] < l[en])
        return sti;
      return en;
    } else if (sti != -1)
      return sti-2;
    else if (en != -1)
      return en-1;
    return 0;
  }
 
  // constructs the segment tree
  static void SegmentTreeConstruction(int ss,
                                      int se, int i)
  {
    if (ss > se)
      return;
    if (ss == se) // leaf
    {
      st[i] = ss;
      return;
    }
    int mid = (ss + se) /2;
 
    SegmentTreeConstruction(ss, mid, left(i));
    SegmentTreeConstruction(mid + 1, se, right(i));
    if (l[st[left(i)]] < l[st[right(i)]])
      st[i] = st[left(i)];
    else
      st[i] = st[right(i)];
  }
 
  // Function to get LCA
  static int LCA(int x, int y)
  {
    if (h[x] > h[y])
    {
      int t = x;
      x = y;
      y = t;
    }
    return e[RMQ(0, l.Count - 1, h[x], h[y], 0)];
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    st = new int[5 * maxn];
     
    // n=number of nodes in the tree
    // q=number of queries to answer
    int n = 15;
    for (int i = 0; i < g.Length; i++)
      g[i] = new List<int>();
 
    // making the tree
    /*
                   1
                 / | \
                2  3  4
                   |   \
                   5    6
                 / |  \
               8   7    9 (right of 5)
                 / | \   | \
               10 11 12 13 14
                      |
                      15
  */
    add_edge(1, 2);
    add_edge(1, 3);
    add_edge(1, 4);
    add_edge(3, 5);
    add_edge(4, 6);
    add_edge(5, 7);
    add_edge(5, 8);
    add_edge(5, 9);
    add_edge(7, 10);
    add_edge(7, 11);
    add_edge(7, 12);
    add_edge(9, 13);
    add_edge(9, 14);
    add_edge(12, 15);
    level[1] = 1;
    leveling(1);
    dfs(1);
    setting_l(n);
    setting_h(n);
    SegmentTreeConstruction(0, l.Count - 1, 0);
    Console.Write(LCA(10, 15) +"\n");
    Console.Write(LCA(11, 14) +"\n");
  }
}
 
// This code is contributed by gauravrajput1
 
 

Javascript




<script>
 
    // JavaScript code to find LCA of given
    // two nodes in a tree
     
    let maxn = 100005;
    function left(i)
    {
      return  (2 * i + 1);
    }
    function right(i) { return 2 * i + 2;}
 
    // the graph
    let g = new Array(maxn);
 
    // level of each node
    let level = new Array(maxn);
    level.fill(0);
    let e = [];
    let l= [];
    let h = new Array(maxn);
    h.fill(0);
 
    // the segment tree
    let st = new Array(5 * maxn);
    st.fill(0);
 
    // adding edges to the graph(tree)
    function add_edge(u, v)
    {
      g[u].push(v);
      g[v].push(u);
    }
 
    // assigning level to nodes
    function levelling(src)
    {
      for (let i = 0; i < (g[src].length); i++)
      {
        let des = g[src][i];
        if (level[des] != 0)
        {
          level[des] = level[src] + 1;
          levelling(des);
        }
      }
    }
 
    let visited = new Array(maxn);
    visited.fill(false);
 
    // storing the dfs traversal
    // in the array e
    function dfs(src)
    {
      e.push(src);
      visited[src] = true;
      for (let i = 0; i < (g[src]).length; i++)
      {
        let des = g[src][i];
        if (!visited[des])
        {
          dfs(des);
          e.push(src);
        }
      }
    }
 
    // making the array l
    function setting_l(n)
    {
      for (let i = 0; i < e.length; i++)
        l.push(level[e[i]]);
    }
 
    // making the array h
    function setting_h(n)
    {
      for (let i = 0; i <= n; i++)
        h[i] = -1;
      for (let i = 0; i < e.length; i++)
      {
 
        // if is already stored
        if (h[e[i]] == -1)
          h[e[i]] = i;
      }
    }
 
    // Range minimum query to return the index
    // of minimum in the subarray L[qs:qe]
    function RMQ(ss, se, qs, qe, i)
    {
      if (ss > se)
        return -1;
 
      // out of range
      if (se < qs || qe < ss)
        return -1;
 
      // in the range
      if (qs <= ss && se <= qe)
        return st[i];
 
      let mid = parseInt((ss + se)/2 , 10);
      let St = RMQ(ss, mid, qs, qe, left(i));
      let en = RMQ(mid + 1, se, qs, qe, right(i));
 
      if (St != -1 && en != -1)
      {
        if (l[St] < l[en])
          return St;
        return en;
      } else if (St != -1)
        return St-2;
      else if (en != -1)
        return en-1;
      return 0;
    }
 
    // constructs the segment tree
    function SegmentTreeConstruction(ss, se, i)
    {
      if (ss > se)
        return;
      if (ss == se) // leaf
      {
        st[i] = ss;
        return;
      }
      let mid = parseInt((ss + se) /2, 10);
 
      SegmentTreeConstruction(ss, mid, left(i));
      SegmentTreeConstruction(mid + 1, se, right(i));
      if (l[st[left(i)]] < l[st[right(i)]])
        st[i] = st[left(i)];
      else
        st[i] = st[right(i)];
    }
 
    // Function to get LCA
    function LCA(x, y)
    {
      if (h[x] > h[y])
      {
        let t = x;
        x = y;
        y = t;
      }
      return e[RMQ(0, l.length - 1, h[x], h[y], 0)];
    }
     
    // n=number of nodes in the tree
    // q=number of queries to answer
    let n = 15, q = 5;
    for (let i = 0; i < g.length; i++)
      g[i] = [];
  
    // making the tree
    /*
                   1
                 / | \
                2  3  4
                   |   \
                   5    6
                 / |  \
               8   7    9 (right of 5)
                 / | \   | \
               10 11 12 13 14
                      |
                      15
  */
    add_edge(1, 2);
    add_edge(1, 3);
    add_edge(1, 4);
    add_edge(3, 5);
    add_edge(4, 6);
    add_edge(5, 7);
    add_edge(5, 8);
    add_edge(5, 9);
    add_edge(7, 10);
    add_edge(7, 11);
    add_edge(7, 12);
    add_edge(9, 13);
    add_edge(9, 14);
    add_edge(12, 15);
    level[1] = 1;
    levelling(1);
    dfs(1);
    setting_l(n);
    setting_h(n);
    SegmentTreeConstruction(0, l.length - 1, 0);
    document.write(LCA(10, 15) +"</br>");
    document.write(LCA(11, 14) +"</br>");
   
</script>
 
 
Output
7 5

Time Complexity: The arrays defined are stored in O(n). The segment tree construction also takes O(n) time. The LCA function calls the function RMQ which takes O(logn) per query (as it uses the segment tree). So overall time complexity is O(n + q * logn).
Auxiliary Space: O(n)



Next Article
Lowest Common Ancestor in a Binary Tree

A

Amritya Vagmi
Improve
Article Tags :
  • Computer Subject
  • DSA
  • Graph
  • Tree
  • LCA
Practice Tags :
  • Graph
  • Tree

Similar Reads

  • Lowest Common Ancestor in a Binary Tree using Parent Pointer
    Given values of two nodes in a Binary Tree, find the Lowest Common Ancestor (LCA). It may be assumed that both nodes exist in the tree. For example, consider the Binary Tree in diagram, LCA of 10 and 14 is 12 and LCA of 8 and 14 is 8. Let T be a rooted tree. The lowest common ancestor between two no
    15+ min read
  • Lowest Common Ancestor in a Binary Tree
    Given the root of a Binary Tree with all unique values and two node values n1 and n2, the task is to find the lowest common ancestor of the given two nodes. The Lowest Common Ancestor (or LCA) is the lowest node in the tree that has both n1 and n2 as descendants. In other words, the LCA of n1 and n2
    15+ min read
  • Lowest Common Ancestor in Parent Array Representation
    Given a binary tree represented as parent array, find Lowest Common Ancestor between two nodes 'm' and 'n'. In the above diagram, LCA of 10 and 14 is 12 and LCA of 10 and 12 is 12. Make a parent array and store the parent of ith node in it. Parent of root node should be -1. Now, access all the nodes
    6 min read
  • LCA in BST - Lowest Common Ancestor in Binary Search Tree
    Given two nodes n1 and n2 of a Binary Search Tree, find the Lowest Common Ancestor (LCA). You may assume that both values exist in the tree. The Lowest Common Ancestor between two nodes n1 and n2 is defined as the lowest node that has both n1 and n2 as descendants (where we allow a node to be a desc
    15+ min read
  • K-th ancestor of a node in Binary Tree | Set 3
    Given a binary tree in which nodes are numbered from 1 to N. Given a node and a positive integer K. We have to print the Kth ancestor of the given node in the binary tree. If there does not exist any such ancestor then print -1.For example in the below given binary tree, 2nd ancestor of node 4 and 5
    7 min read
  • Lowest Common Ancestor of the deepest leaves of a Binary Tree
    Given a Binary Tree consisting of N nodes having distinct values from the range [1, N], the task is to find the lowest common ancestor of the deepest leaves of the binary tree. Examples: Input: Output: 1Explanation: The deepest leaf nodes of the tree are {8, 9, 10}. Lowest common ancestor of these n
    10 min read
  • Kth ancestor of a node in binary tree | Set 2
    Given a binary tree in which nodes are numbered from 1 to n. Given a node and a positive integer K. We have to print the Kth ancestor of the given node in the binary tree. If there does not exist any such ancestor then print -1.For example in the below given binary tree, the 2nd ancestor of 5 is 1.
    7 min read
  • Lowest Common Ancestor for a Set of Nodes in a Rooted Tree
    Given a rooted tree with N nodes, the task is to find the Lowest Common Ancestor for a given set of nodes V of that tree. Examples: Input: 1 / | \ 2 3 4 / \ | | 5 6 7 10 / \ 8 9 V[] = {7, 3, 8, 9} Output: 3 Input: 1 / | \ 2 3 4 / \ | | 5 6 7 10 / \ 8 9 V[] = {4, 6, 7} Output: 1 Approach: We can obse
    12 min read
  • K-th ancestor of a node in Binary Tree
    Given a binary tree in which nodes are numbered from 1 to n. Given a node and a positive integer K. We have to print the K-th ancestor of the given node in the binary tree. If there does not exist any such ancestor then print -1.For example in the below given binary tree, 2nd ancestor of node 4 and
    15+ min read
  • Least Common Ancestor of any number of nodes in Binary Tree
    Given a binary tree (not a binary search tree) and any number of Key Nodes, the task is to find the least common ancestor of all the key Nodes. Following is the definition of LCA from Wikipedia: Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest n
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences