Lowest Common Ancestor in a BST
Submissions: 18813   Accuracy:


  Difficulty: Easy   Marks: 2

Given a Binary Search Tree and 2 nodes value n1 and n2, your task is to find the lowest common ancestor(LCA) of the two nodes .

Input Format:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains three lines of input.
The first line contains N, the number of nodes of the BST.
The second line contains the values of the nodes, each separated by a space.
The third line contains the two values n1 and n2 separated by a space.

Output Format:
For each testcase, in a new line, print the LCA of n1 and n2.

Your Task:
This is a function problem. You don't have to take any input. You are required to complete the function LCA that takes node, n1, n2 as parameters and returns the node that is LCA of n1 and n2.

1 <= T <= 100
1 <= N <= 100
1 <= Node value <= 1000

5 4 6 3 7 8
7 8


The BST in above test case will look like

   /  \ 
  4  6
 /      \
3        7
here the LCA of 7 and 8 is 7 .


** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Amit Khandelwal, Harshit Sidhwa
Author: Shubham Joshi 1

Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.

to report an issue on this page.