Given a Binary Search Tree of size N and 2 nodes value n1 and n2, your task is to find the lowest common ancestor(LCA) of the two nodes .
Note: Duplicates are not inserted in the BST.

Input Format:
First line of input contains the number of test cases T. For each test case, there will be two line of input. First line is a string representing the tree as described below and second line contains two space seperated integers N1 and N2: 

  1. The values in the string are in the order of level order traversal of the tree where, numbers denotes node values, and a character “N” denotes NULL child.

  2. For example:

    For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N

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 root node, n1, n2 as parameters and returns the node that is LCA of n1 and n2.

1 <= T <= 100
1 <= N <= 104

5 4 6 3 N N 7 N N N 8
7 8
2 1 3
1 3



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

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.

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

to report an issue on this page.