Dsa
Binary Search Tree
Medium
BST Lowest Common Ancestor
Given a binary search tree and two nodes, find their lowest common ancestor (LCA). The LCA is defined as the deepest node that is an ancestor to both nodes. Write a program that reads the tree and the two nodes, and prints the value of the LCA if it exists. If one or both nodes are not present in the tree, print 'Not Found'.
Input Format:
- The first line contains an integer N, the number of nodes in the BST.
- The next N lines each contain an integer representing the node value.
- The last line contains two space-separated integers representing the two nodes.
Output Format:
- Print the value of the LCA or 'Not Found'.
Example:
Input:
7
4
2
6
1
3
5
7
1 3
Output:
2
Key concepts
binary_search_treelcarecursion
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now