Back to DSA
Lowest Common Ancestor of a Binary Tree
mediumIn a binary tree (not necessarily a BST), find the lowest common ancestor of two specified nodes. The lowest common ancestor is the deepest node that is an ancestor of both target nodes. A node is considered an ancestor of itself.
Examples
Example 1:
Input:
root = [10,5,15,3,7,12,20], p = 3, q = 7Output:
5 Example 2:
Input:
root = [10,5,15,3,7,12,20], p = 5, q = 20Output:
10Hints
1234567