Search⌘ K

Find Lowest Common Ancestor in a Binary Tree

Explore how to find the lowest common ancestor of two nodes in a binary tree by implementing a function that tracks parent nodes and uses set operations for quick ancestor retrieval. Understand the time and space complexity of the algorithm to improve your coding interview skills with tree-based problems.

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 ...