Find Lowest Common Ancestor in a Binary Tree

Given a binary tree and two of its nodes, find the lowest common ancestor.

Statement

Given a binary tree and two of its nodes, find their lowest common ancestor (LCA).

Implement the function lowestCommonAncestor(root, node1, node2), where root is the root node of the binary tree. The function should return the value of the LCA node.

Example

Consider the following binary tree as an example, where 2020 is the LCA of 1515 and 77:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.