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:
Find K smallest leaf nodes from a given Binary Tree
Next article icon

Find LCA for K queries in Complete Binary Tree

Last Updated : 05 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer n. There is a complete binary tree with 2n - 1 nodes. The root of that tree is the node with the value 1, and every node with a value x has two children where the left node has the value 
2*x and the right node has the value 2*x + 1, you are given K queries of type (ai, bi), and the task is to return the LCA for the node pair ai and bi for all K queries.

Examples:

Input:  n = 5, queries = [ { 17, 21 }, { 23, 5 }, { 15, 7 }, { 3, 21 }, { 31, 9 }, { 5, 15 }, { 11, 2 }, { 19, 7 } ]

Complete binary tree for given input n=5

Output:  [ 2, 5, 7, 1, 1, 1, 2, 1 ]

Input:  n = 3, queries = [ {2, 5}, {3, 6}, {4, 1}, {7, 3} ]

Complete binary tree for given input n=3

Output: [2, 3, 1, 3]

Approach: The problem can be solved based on the following idea:

As all values on a level are smaller than values on the next level. Check which node is having greater value in a query, and divide it by 2 to reach its parent node. Repeat this step until we get common element. 

Follow the steps to solve the problem:

  • In a query, we are having 2 nodes a and b, whose lowest common ancestor we have to find.
  • By dividing the value of the node by 2, we will always get the parent node value.
  • From a and b whichever node is having greater value divide by 2. So, as to move towards the root of the root.
  • When a and b becomes equal, the common ancestor between them is got and returned.  

Below is the implementation for the approach discussed:

C++
// C++ code for the above approach #include <bits/stdc++.h> using namespace std;  // Function to find lca for // given two nodes in tree int helper(int a, int b) {      while (a != b) {          if (a > b)             a = a / 2;          else             b = b / 2;     }      return a; }  // Driver code int main() {      // 2^n - 1 nodes in complete     // binary tree     int n = 5;      // Queries input vector     vector<vector<int> > queries         = { { 17, 21 }, { 23, 5 }, { 15, 7 }, { 3, 21 }, { 31, 9 }, { 5, 15 }, { 11, 2 }, { 19, 7 } };      // Processing each query in     // queries vector     for (auto e : queries) {          // Function call         int lca = helper(e[0], e[1]);          cout << lca << ' ';     }      return 0; } 
Java
// Java code for the above approach import java.io.*;  class GFG {     // Function to find lca for     // given two nodes in tree     public static int helper(int a, int b)     {          while (a != b) {              if (a > b)                 a = a / 2;              else                 b = b / 2;         }          return a;     }      // Driver Code     public static void main(String[] args)     {         // 2^n - 1 nodes in complete         // binary tree         int n = 5;          // Queries input vector         int queries[][] = { { 17, 21 }, { 23, 5 },                             { 15, 7 },  { 3, 21 },                             { 31, 9 },  { 5, 15 },                             { 11, 2 },  { 19, 7 } };          // Processing each query in         // queries vector         for (int e[] : queries) {              // Function call             int lca = helper(e[0], e[1]);              System.out.print(lca + " ");         }     } }  // This code is contributed by Rohit Pradhan 
C#
using System; using System.Collections.Generic;  class Program {     // Function to find lca for     // given two nodes in tree     static int helper(int a, int b)     {          while (a != b)         {              if (a > b)                 a = a / 2;              else                 b = b / 2;         }          return a;     }      // Driver code     static void Main(string[] args)     {          // 2^n - 1 nodes in complete         // binary tree         int n = 5;          // Queries input vector         List<List<int>> queries = new List<List<int>> {             new List<int> { 17, 21 },             new List<int> { 23, 5 },             new List<int> { 15, 7 },             new List<int> { 3, 21 },             new List<int> { 31, 9 },             new List<int> { 5, 15 },             new List<int> { 11, 2 },             new List<int> { 19, 7 }         };          // Processing each query in         // queries vector         foreach (var e in queries)         {              // Function call             int lca = helper(e[0], e[1]);              Console.Write(lca + " ");         }      } } // code by ksam24000 
JavaScript
// Function to find lca for // given two nodes in tree function helper(a, b) {     while (a != b) {         if (a > b)             a = Math.floor(a / 2);         else             b = Math.floor(b / 2);     }     return a; }  // Driver code console.log("LCA(s):");  // 2^n - 1 nodes in complete // binary tree let n = 5;  // Queries input array let queries = [ [ 17, 21 ], [ 23, 5 ], [ 15, 7 ], [ 3, 21 ], [ 31, 9 ], [ 5, 15 ], [ 11, 2 ], [ 19, 7 ] ];  // Processing each query in // queries array for (let i = 0; i < queries.length; i++) {     let e = queries[i];      // Function call     let lca = helper(e[0], e[1]);      console.log(lca + ' '); } 
Python3
# Function to find lca for # given two nodes in tree def helper(a, b):     while (a != b):         if (a > b):             a = a // 2         else:             b = b // 2     return a  # Driver code print("LCA(s):")  # 2^n - 1 nodes in complete # binary tree n = 5  # Queries input list queries = [ [ 17, 21 ], [ 23, 5 ], [ 15, 7 ], [ 3, 21 ], [ 31, 9 ], [ 5, 15 ], [ 11, 2 ], [ 19, 7 ] ]  # Processing each query in # queries list for e in queries:     # Function call     lca = helper(e[0], e[1])      print(lca, end=' ') 

Output
2 5 7 1 1 1 2 1 

Time Complexity: O(log2(max(a,b)), here we divide number a or b every time with 2 so it will cost log2() complexity and here we are doing it for a and b so a max of(a,b) will be the number which takes worst time so overall time complexity will be O(log2(max(a,b))) to find LCA of two node a&b.
Auxiliary Space: O(1)

Related Articles:

  • Introduction to Tree – Data Structure and Algorithm Tutorials

Next Article
Find K smallest leaf nodes from a given Binary Tree

C

codelohani
Improve
Article Tags :
  • Tree
  • Technical Scripter
  • DSA
  • Technical Scripter 2022
Practice Tags :
  • Tree

Similar Reads

  • Find the largest Complete Subtree in a given Binary Tree
    Given a Binary Tree, the task is to find the size and also the inorder traversal of the largest Complete sub-tree in the given Binary Tree. Complete Binary Tree - A Binary tree is a Complete Binary Tree if all levels are filled except possibly the last level and the last level has all keys as left a
    13 min read
  • Find the closest leaf in a Binary Tree
    Given a Binary Tree and a key 'k', find distance of the closest leaf from 'k'. Examples: A / \ B C / \ E F / \ G H / \ / I J K Closest leaf to 'H' is 'K', so distance is 1 for 'H' Closest leaf to 'C' is 'B', so distance is 2 for 'C' Closest leaf to 'E' is either 'I' or 'J', so distance is 2 for 'E'
    14 min read
  • Find K smallest leaf nodes from a given Binary Tree
    Given a binary tree and an integer K, the task is to find the K smallest leaf nodes from the given binary tree. The number of leaf nodes will always be at least K. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ \ 21 8 19Output: 6 8 19Explanation:There are 4 leaf nodes in the above binary tree out of
    7 min read
  • LCA for n-ary Tree | Constant Query O(1)
    We have seen various methods with different Time Complexities to calculate LCA in n-ary tree:- Method 1 : Naive Method ( by calculating root to node path) | O(n) per query Method 2 :Using Sqrt Decomposition | O(sqrt H) Method 3 : Using Sparse Matrix DP approach | O(logn) Lets study another method th
    15+ min read
  • Find LCA in Binary Tree using RMQ
    The article describes an approach to solving the problem of finding the LCA of two nodes in a tree by reducing it to an RMQ problem. The Lowest Common Ancestor (LCA) of two nodes u and v in a rooted tree T is defined as the node located farthest from the root that has both u and v as descendants.For
    15+ min read
  • Find the closest element in Binary Search Tree
    Given a binary search tree and a target node K. The task is to find the node with a minimum absolute difference with the given target value K. Examples: Input : k = 4Output: 4 Input : k = 18Output: 17 Input : k = 12Output: 9 Input: k=2Output: 3 [Naive Approach] By using Inorder Traversal:Store Inord
    5 min read
  • Find parent of each node in a tree for multiple queries
    Given a tree with N vertices numbered from 0 to N – 1 and Q query containing nodes in the tree, the task is to find the parent node of the given node for multiple queries. Consider the 0th node as the root node and take the parent of the root node as the root itself.Examples: Tree: 0 / \ 1 2 | / \ 3
    8 min read
  • Complete Binary Tree
    We know a tree is a non-linear data structure. It has no limitation on the number of children. A binary tree has a limitation as any node of the tree has at most two children: a left and a right child. What is a Complete Binary Tree?A complete binary tree is a special type of binary tree where all t
    7 min read
  • Find value K in given Complete Binary Tree with values indexed from 1 to N
    Given a complete binary tree with values indexed from 1 to N and a key K. The task is to check whether a key exists in the tree or not. Print "true" if the key exists, otherwise print "false". Complete Binary Tree: A Binary Tree is a complete Binary Tree if all the levels are completely filled excep
    11 min read
  • Check if value exists in level-order sorted complete binary tree
    Given a level-order sorted complete binary tree, the task is to check whether a key exists in it or not. A complete binary tree has every level except possibly the last, completely filled, with all nodes as far left as possible. Examples: 7 / \ 10 15 / \ / \ 17 20 30 35 / \ / 40 41 50 Input: Node =
    15+ 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