Question bank › Trees
Dsa Trees Medium

Lowest Common Ancestor in a Binary Tree

Given a binary tree and two values, find the lowest common ancestor (LCA) of the two nodes that have the given values. Read the tree structure from standard input: - The first line contains an integer, n, the number of nodes in the tree. - The next n lines list each node's value and the left and right child indices. A child index of -1 indicates no child. - The last line contains two integers, p and q, the values for which the LCA needs to be found. Output a single integer representing the value of the LCA. Example: Input: 5 3 1 2 1 -1 -1 2 -1 -1 5 -1 -1 4 -1 -1 4 1 Output: 3

Key concepts

binary treelowest common ancestortraversal

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
Part of Praxari's verified interview question bank. We show the prompt and concepts to practise with — never a copy-paste solution.