Find LCA for K queries in Complete Binary Tree
Last Updated : 05 Mar, 2023
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=' ')
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:
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