Solution: Lowest Common Ancestor of a Binary Tree III
Let’s solve the Lowest Common Ancestor of a Binary Tree III problem using the Two Pointers pattern.
We'll cover the following
Statement
You are given two nodes, p
and q
. The task is to return their lowest common ancestor (LCA). Both nodes have a reference to their parent node. The tree’s root is not provided; you must use the parent pointers to find the nodes’ common ancestor.
Note: The lowest common ancestor of two nodes,
p
andq
, is the lowest node in the binary tree, with bothp
andq
as descendants.In a tree, a descendant of a node is any node reachable by following edges downward from that node, including the node itself.
Constraints:
Node.data
The number of nodes in the tree is in the range
All
Node.data
are unique.p
!=q
Both
p
andq
are present in the tree.
Solution
This solution finds the lowest common ancestor (LCA) of two nodes in a binary tree using a smart two-pointer approach. We start by placing one pointer at node p
and the other at node q
. Both pointers move up the tree at each step by following their parent pointers. If a pointer reaches the root (i.e., its parent is None
), it jumps to the other starting node. This process continues until the two pointers meet. The key idea is that by switching starting points after reaching the top, both pointers end up traveling the same total distance, even if p
and q
are at different depths. When they meet, that meeting point is their lowest common ancestor.
The steps of the algorithm are as follows:
Initialize two pointers:
ptr1
starting atp
andptr2
starting atq
.While
ptr1
andptr2
are not pointing to the same node:If
ptr1
has a parent, moveptr1
toptr1.parent
; otherwise, setptr1 = q
.If
ptr2
has a parent, moveptr2
toptr2.parent
; otherwise, setptr2 = p
.
When
ptr1 == ptr2
, returnptr1
. This node is the lowest common ancestor (LCA) ofp
andq
.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.