Dsa
Binary Search Tree
Medium
Lowest Common Ancestor
Given the root of a binary search tree and two node values, find the lowest common ancestor (LCA) of the two nodes. The LCA is defined as the lowest node in the tree that has both elements as descendants.
Input format:
- The first line contains an integer n (the number of nodes).
- The next n lines contain three integers: val, left_index, right_index.
- The last line contains two integers u and v, the values of the nodes.
Output format:
- Print the value of the LCA node.
Example input:
5
20 1 2
10 3 4
30 -1 -1
5 -1 -1
15 -1 -1
5 30
Example output:
20
Key concepts
binary_search_treeancestor
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