Given that 2 elements are present in the tree, write a function to find the LCA(Least Common Ancestor) of the 2 elements.

Given that 2 elements are present in the tree, write a function to find the LCA(Least Common Ancestor) of the 2 elements.
A.
Code:
public void lca(Tree root,int n1, int n2)
{
	while (root != NULL)
        {
            if (root.data() > n1 && root.data() > n2)
            root = root.right();
            else if (root.data() < n1 &#038;&#038; root.data() < n2)
            root = root.left();
	    else break;
        }
        System.out.println(root.data());
}
B.
Code:
public void lca(Tree root,int n1, int n2)
{
    while (root != NULL)
    {
        if (root.data() > n1 && root.data() < n2)
        root = root.left();
        else if (root.data() < n1 &#038;&#038; root.data() > n2)
        root = root.right();
	else break;
    }
    System.out.println(root.data());
}
C.
Code:
public void lca(Tree root,int n1, int n2)
{
    while (root != NULL)
    {
        if (root.data() > n1 && root.data() > n2)
        root = root.left();
        else if (root.data() < n1 &#038;&#038; root.data() < n2)
        root = root.right();
	else break;
    }
    System.out.println(root.data());
}
D.
Code:
public void lca(Tree root,int n1, int n2)
{
    while (root != NULL)
    {
        if (root.data() > n1 && root.data() > n2)
        root = root.left.left();
        else if (root.data() < n1 &#038;&#038; root.data() < n2)
        root = root.right.right();
	else break;
    }
    System.out.println(root.data());
}
 
Answer: C
Explanation: The property of a binary search tree is that the lesser elements are to the left and greater elements are to the right, we use this property here and iterate through the tree such that we reach a point where the 2 elements are on 2 different sides of the node, this becomes the least common ancestor of the 2 given elements.
 

Tìm kiếm

Back
Top