Solution: Lowest Common Ancestor of a Binary Tree
Explore how to determine the lowest common ancestor in a binary tree by applying depth-first search. Understand the recursive strategy that identifies whether nodes are descendants of each other or their common ancestor. Learn to implement this in C# with attention to runtime and space complexities.
We'll cover the following...
Statement
Given the root node of a binary tree with nodes, your task is to find the lowest common ancestor of two of its nodes, p and q.
Note: The lowest common ancestor of two nodes,
pandq, is defined as the lowest node in the binary tree that has bothpandqas descendants.A node can also be a descendant of itself. For example, if
qis a descendant ofp, and we know thatpis a descendant of itself, thenpwill be the lowest common ancestor ofpandq.
Constraints:
- All
Node.dataare unique. p