Lowest Common Ancestor

00:00
MediumTreeDFSRecursion
AmazonMicrosoftFacebook

Find the Lowest Common Ancestor (LCA) of two nodes p and q in a binary tree. LCA is the deepest node that has both p and q as descendants (a node is a descendant of itself).

Examples

Input → tree=[3,5,1,6,2,0,8], p=5,q=1
Output → 3
Input → same tree, p=5,q=4
Output → 5
Note: 5 is ancestor of 4
Input → p=q
Output → return that node