Given that 2 elements are present in the tree, write a function to find the LCA(Least Common Ancestor) of the 2 elements.
A.
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 && root.data() < n2)
root = root.left();
else break;
}
System.out.println(root.data());
}B.
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 && root.data() > n2)
root = root.right();
else break;
}
System.out.println(root.data());
}C.
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 && root.data() < n2)
root = root.right();
else break;
}
System.out.println(root.data());
}D.
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 && root.data() < n2)
root = root.right.right();
else break;
}
System.out.println(root.data());
}Answer: Option C
Related Questions on Binary Search Trees(B Tree)
A. O(1)
B. O(log n)
C. O(n)
D. O(n log n)
Which traversal method of a BST will produce a sorted sequence of node values?
A. Inorder
B. Preorder
C. Postorder
D. Level-order
What is the maximum number of children a node in a Binary Search Tree (BST) can have?
A. 1
B. 2
C. 3
D. Any number
How can you determine if a Binary Tree is a Binary Search Tree (BST)?
A. Verify if all nodes in the left subtree are less than the root and all nodes in the right subtree are greater than the root.
B. Check if the tree is balanced.
C. Ensure all nodes have exactly two children.
D. Verify the height of the tree.

Join The Discussion