Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

LCA of three Nodes

Easy
0/40
Average time to solve is 20m
profile
Contributed by
5523 upvotes
Asked in companies
AccenturePaytm (One97 Communications Limited)Microsoft

Problem statement

You have been given a Binary Tree of 'N' nodes where the nodes have integer values and three integers 'N1', 'N2', and 'N3'. Find the LCA(Lowest Common Ancestor) of the three nodes represented by the given three('N1', 'N2', 'N3') integer values in the Binary Tree.

For example:

For the given binary tree: the LCA of (7,8,10) is 1
Note:
All of the node values of the binary tree will be unique.

N1, N2, and N3  will always exist in the binary tree.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains a single integer T, representing the number of test cases or queries to be run. 

Then the T test cases follow. 

The first line of each test case contains three single space-separated integers N1, N2, and N3, denoting the nodes of which LCA is to be calculated.

The second line of each test case contains elements in the level order form. The line consists of values of nodes separated by a single space. In case a node is null, we take -1 in its place.

For example, the input for the tree depicted in the below image would be :

alt text

1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1

Explanation :

Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 2
Right child of 1 = 3

Level 3 :
Left child of 2 = 4
Right child of 2 = null (-1)
Left child of 3 = 5
Right child of 3 = 6

Level 4 :
Left child of 4 = null (-1)
Right child of 4 = 7
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 6 = null (-1)
Right child of 6 = null (-1)

Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)

The first not-null node (of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.
The input ends when all nodes at the last level are null (-1).
Note :
The above format was just to provide clarity on how the input is formed for a given tree. 
The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:

1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output Format:
For each test case,  return the node representing LCA.
Note
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 10^5
0 <= node data <= 10^9
0 <= N1 <= 10^9
0 <= N2 <= 10^9
0 <= N3 <= 10^9

Time Limit: 1sec
Sample Input 1:
1
8 9 11
1 2 3 4 5 6 7 8 9 -1 -1 -1 -1 -1 -1 10 -1 11 -1 -1 -1 -1 -1
Sample Output 1:
4
Sample Input 2:
2
7 8 2
1 2 3 4 5 6 7 8 9 -1 -1 -1 -1 -1 -1 10 -1 11 -1 -1 -1 -1 -1
5 6 7
1 2 3 4 5 6 7 8 9 -1 -1 -1 -1 -1 -1 10 -1 11 -1 -1 -1 -1 -1
Sample Output 2:
1
1
Explanation to Sample Input 2:
For both inputs, the binary tree will be represented as

For the first test case, the LCA of 7,8,2 in the given tree is 2 

For the second test case. the LCA of 5,6,7 in the given tree is 1,   


Hints:
1. Think of finding LCA from the paths to all three nodes.
Hint

Think of a recursive solution.

Approaches (2)
By Storing Paths
  • A simple solution would be to store the path from the root to ‘N1’, the path from the root to ‘N2’, and the path from the root to ‘N3’ in the three auxiliary Lists/Array.
  • Now, to store the path from the root to any node ‘X’ we create a recursive function that traverses the different path in the binary tree to find any node ‘X’:
    1. If ‘ROOT’ == null return true
    2. Add the root data to List/Array
    3. If root data = ‘X’ return true
    4. If ‘X’ is found in any of the subtrees either left or right then return true
    5. Else remove the current root data from the List/Array and then return false
  • Then we traverse all lists simultaneously till the values in the list match. The last matched value will be the LCA. If the end of one array is reached then the last seen value is LCA.
Time Complexity

O(N), where N is the total number of nodes in the given binary tree.

 

In the worst case, the tree is traversed thrice to find paths of N1, N2, and N3 O(N), and then the stored path list O(N) is traversed. Thus a total of O(N).

Space Complexity

O(N), where N is the total number of nodes in the given binary tree.

 

In the worst case, we will store all the nodes in the list as a path from the root to the node. And we will have all the nodes of the Binary Tree in the recursion stack O(N). Thus a total of O(N).

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
LCA of three Nodes
All tags
Sort by
Search icon

Interview problems

Java Solution for this Question ( LCA of Three Nodes )

import java.util.Scanner;

public class Solution {
    public static BinaryTreeNode<Integer> lcaOfThreeNodes(BinaryTreeNode<Integer> root, int node1, int node2, int node3) {
        // Base case
        if (root == null || root.data == node1 || root.data == node2 || root.data == node3) {
            return root;
        }

        // Recursive calls
        BinaryTreeNode<Integer> leftLCA = lcaOfThreeNodes(root.left, node1, node2, node3);
        BinaryTreeNode<Integer> rightLCA = lcaOfThreeNodes(root.right, node1, node2, node3);

        // If both left and right children returned non-null, this is the LCA
        if (leftLCA != null && rightLCA != null) {
            return root;
        }

        // Otherwise, return the non-null child
        return (leftLCA != null) ? leftLCA : rightLCA;
    }

    // Helper method to build a binary tree from a given array
    public static BinaryTreeNode<Integer> buildTree(Integer[] nodes) {
        if (nodes.length == 0 || nodes[0] == null) return null;

        BinaryTreeNode<Integer> root = new BinaryTreeNode<>(nodes[0]);
        BinaryTreeNode<Integer>[] treeNodes = new BinaryTreeNode[nodes.length];
        treeNodes[0] = root;

        for (int i = 1; i < nodes.length; i++) {
            if (nodes[i] != null) {
                treeNodes[i] = new BinaryTreeNode<>(nodes[i]);
                if (i % 2 == 1) { // Left child
                    treeNodes[(i - 1) / 2].left = treeNodes[i];
                } else { // Right child
                    treeNodes[(i - 2) / 2].right = treeNodes[i];
                }
            }
        }

        return root;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Read the number of test cases
        int T = scanner.nextInt();
        while (T-- > 0) {
            // Read the nodes for LCA
            int node1 = scanner.nextInt();
            int node2 = scanner.nextInt();
            int node3 = scanner.nextInt();

            // Read the binary tree nodes
            Integer[] nodes = new Integer[scanner.nextInt()];
            for (int i = 0; i < nodes.length; i++) {
                int value = scanner.nextInt();
                nodes[i] = (value == -1) ? null : value; // -1 indicates null
            }

            // Build the tree
            BinaryTreeNode<Integer> root = buildTree(nodes);

            // Find and print the LCA
            BinaryTreeNode<Integer> lca = lcaOfThreeNodes(root, node1, node2, node3);
            System.out.println(lca.data);
        }

        scanner.close();
    }
}

java

15 views
0 replies
1 upvote

Interview problems

CPP - Brute Force Approach : O(n) worst case

BinaryTreeNode<int>* lcaOfThreeNodes(BinaryTreeNode<int>* root, int node1, int node2, int node3) {

    // Write your code here.
	//base case
	if(root == NULL){
		return NULL;
	}

	if (root->data == node1 || root->data == node2 || root->data == node3 ){
			return root;
	}




	BinaryTreeNode<int>* leftLCA = lcaOfThreeNodes(root->left, node1, node2, node3);
	BinaryTreeNode<int>*rightLCA = lcaOfThreeNodes(root->right, node1, node2,node3);

	if(leftLCA != NULL && rightLCA != NULL){
		return root;
	}

	//if all node are present only anyone side
	BinaryTreeNode<int>* potentialLCA = (leftLCA != NULL) ? leftLCA:rightLCA;


	if(potentialLCA != NULL){
		return potentialLCA;
	}
	else{
		return NULL;
	}




}
83 views
0 replies
0 upvotes

Interview problems

Software developer

Html css Javascript 

25 views
0 replies
0 upvotes

Interview problems

easy to understand ,better than 99,8% sol in c++.

 

BinaryTreeNode<int>* lcaOfThreeNodes(BinaryTreeNode<int>* root, int node1, int node2, int node3) {

    if (root == nullptr) {

        return nullptr;

    }

    if (root->data == node1 || root->data == node2 || root->data == node3) {

        return root;

    }

 

    BinaryTreeNode<int>* leftLCA = lcaOfThreeNodes(root->left, node1, node2, node3);

    BinaryTreeNode<int>* rightLCA = lcaOfThreeNodes(root->right, node1, node2, node3);

 

    if (leftLCA != nullptr && rightLCA != nullptr) {

        return root;

    }

 

    return (leftLCA != nullptr) ? leftLCA : rightLCA;

}

 

138 views
0 replies
0 upvotes

Interview problems

JAVA-LCA OF 3 NODES

 

/**********************************************************

    Following is the Binary Tree Node class.

 

    class BinaryTreeNode<T> {

        T data;

        BinaryTreeNode<T> left;

        BinaryTreeNode<T> right;

 

        public BinaryTreeNode(T data) {

        this.data = data;

        }

    }

    

***********************************************************/

 

public class Solution {

    public static BinaryTreeNode<Integer> lcaOfThreeNodes(BinaryTreeNode<Integer> root, int node1, int node2,

            int node3) {

         if(root==null ||root.data==node1 ||root.data==node2 ||root.data==node3 )

         {

             return root;

         }

         BinaryTreeNode<Integer> left=lcaOfThreeNodes(root.left, node1, node2, node3);

         BinaryTreeNode<Integer> right=lcaOfThreeNodes(root.right, node1, node2, node3);

         if(left==null)

         {

             return right;

         }

         if(right==null)

         {

             return left;

         }

         return root;

    }

}

 

103 views
2 replies
0 upvotes

Interview problems

JAVA BEST SOLUTION

public class Solution {

    public static BinaryTreeNode<Integer> lcaOfThreeNodes(BinaryTreeNode<Integer> root, int node1, int node2,

            int node3) {

        if ((root == null) || (root.data == node1 || root.data == node2 || root.data == node3)) {

            return root;

        }

        BinaryTreeNode<Integer> leftAns = lcaOfThreeNodes(root.left, node1, node2, node3);

        BinaryTreeNode<Integer> rightAns = lcaOfThreeNodes(root.right, node1, node2, node3);

        if (leftAns != null && rightAns != null)

            return root;

        else if (leftAns != null)

            return leftAns;

        else

            return rightAns;

    }

}

150 views
0 replies
0 upvotes

Interview problems

All test cases passed || Easy recursion || C++ || Easy to understand || Maintain count=3

So tried to find out how this recursion works ??

 

don't worry , I got you covered 

 

See the approach is simple it can even help you fetch 4 or 5 or 6 .. k no of lca 

 

what u need to do is maintain a variable count 

 

if you found a solution node (any node out of 3) just return previous + 1 from that side (yeah u got it right , we are maintaing sum , and if the node doesnt matches then go to its left then right try to find the node and return the prev + 1)

 

if this prev+1 returns 3 then boom your ans is right in front of you thats the node u wanted to cater , return that node  via a global variable 

 

 

heres the code:

 

/**********************************************************

    Following is the Binary Tree Node class structure.

 

    template <typename T>

    class BinaryTreeNode {

    public :

        T data;

        BinaryTreeNode<T> *left;

        BinaryTreeNode<T> *right;

 

        BinaryTreeNode(T data) {

            this -> data = data;

            left = NULL;

            right = NULL;

        }

    };

 

***********************************************************/

BinaryTreeNode<int>* ret = nullptr;

 

int countMatches(BinaryTreeNode<int>* root, int node1, int node2, int node3) {

    if (root == nullptr) {

        return 0;

    }

 

    int count = (root->data == node1) + (root->data == node2) + (root->data == node3);

 

    int leftCount = countMatches(root->left, node1, node2, node3);

    int rightCount = countMatches(root->right, node1, node2, node3);

 

    int total = count + leftCount + rightCount;

 

    if (total == 3 && ret == nullptr) {

        ret = root;

    }

 

    return total;

}

 

BinaryTreeNode<int>* lcaOfThreeNodes(BinaryTreeNode<int>* root, int node1, int node2, int node3) {

    ret = nullptr;

    countMatches(root, node1, node2, node3);

    return ret;

}

 

 

 

 

260 views
0 replies
0 upvotes

Interview problems

C++ || Using recursion

// Method 1 : Using recursion

BinaryTreeNode<int>* lcaOfThreeNodes(BinaryTreeNode<int>* root, int node1, int node2, int node3) {

    

    // Base case

    if(!root || root->data == node1 || root->data == node2 || root->data == node3)

        return root;

    

 

    BinaryTreeNode<int> *left = lcaOfThreeNodes(root->left, node1, node2, node3);

    BinaryTreeNode<int> *right = lcaOfThreeNodes(root->right, node1, node2, node3);

 

    if(!left) return right;

    else if(!right) return left;

    else return root;

 

}

704 views
0 replies
2 upvotes

Interview problems

c++ recursive approach

BinaryTreeNode<int>* lcaOfThreeNodes(BinaryTreeNode<int>* root, int node1, int node2, int node3) {

// Write your code here.

if(root==NULL){

return NULL;

}

if(root->data == node1 || root->data == node2 || root->data == node3){

return root;

}

BinaryTreeNode<int>* left = lcaOfThreeNodes(root->left,node1,node2,node3);

BinaryTreeNode<int>*right = lcaOfThreeNodes(root->right,node1,node2,node3);

if(left!=NULL && right == NULL){

return left;

}

if(left==NULL && right!= NULL){

return right;

}

if(left!=NULL && right!=NULL){

return root;

}

}

 

262 views
0 replies
0 upvotes

Interview problems

easiest way...

BinaryTreeNode<int>* lcaOfThreeNodes(BinaryTreeNode<int>* root, int node1, int node2, int node3) {

  if (root == NULL || root->data == node1 || root->data == node2 || root->data == node3) {

    return root;

  }

  BinaryTreeNode<int> *left = lcaOfThreeNodes(root->left, node1, node2, node3);

  BinaryTreeNode<int> *right =

      lcaOfThreeNodes(root->right, node1, node2, node3);

  if (left == NULL)

    return right;

  else if (right == NULL)

    return left;

  else

    return root;

}

281 views
0 replies
0 upvotes
Full screen
Console