Lowest Common Ancestor of a Binary Tree III - Problem

Imagine you're a genealogist tracing family lineages in a complex family tree. You have two people, and you need to find their closest common ancestor - the most recent person from whom both individuals descended.

In this problem, you're given two nodes p and q in a binary tree, where each node has a special feature: a direct reference to its parent! Your task is to find their Lowest Common Ancestor (LCA) - the deepest node that has both p and q as descendants.

Key points:

  • Each node has val, left, right, and parent references
  • A node can be considered a descendant of itself
  • The LCA is the lowest (deepest) node that contains both nodes in its subtree

The beauty of this version is that with parent pointers, we can traverse upward from any node, opening up elegant solutions!

Input & Output

example_1.py โ€” Basic Tree
$ Input: Tree: [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
โ€บ Output: 3
๐Ÿ’ก Note: The LCA of nodes 5 and 1 is 3, as it's the deepest node that has both 5 and 1 as descendants.
example_2.py โ€” Same Subtree
$ Input: Tree: [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
โ€บ Output: 5
๐Ÿ’ก Note: The LCA of nodes 5 and 4 is 5, since node 4 is a descendant of node 5, making 5 the lowest common ancestor.
example_3.py โ€” Adjacent Nodes
$ Input: Tree: [1,2], p = 1, q = 2
โ€บ Output: 1
๐Ÿ’ก Note: In a simple two-node tree where 2 is a child of 1, the LCA of 1 and 2 is 1 (the root).

Constraints

  • The number of nodes in the tree is in the range [2, 105]
  • -109 โ‰ค Node.val โ‰ค 109
  • All Node.val are unique
  • p โ‰  q
  • p and q exist in the tree

Visualization

Tap to expand
Binary Tree LCA with Parent PointersLCAABCDEFpqPath from p:p โ†’ C โ†’ A โ†’ LCAPath from q:q โ†’ F โ†’ B โ†’ LCAMeeting Point: Lowest Common Ancestor
Understanding the Visualization
1
Start the Journey
Two relatives (p and q) begin tracing their lineage upward using parent pointers
2
Traverse Upward
Both follow their parent links toward older generations simultaneously
3
Switch Paths
When one reaches the family patriarch (root), they switch to trace the other person's lineage
4
Meet at LCA
The synchronized paths ensure they meet at their lowest common ancestor
Key Takeaway
๐ŸŽฏ Key Insight: With parent pointers, we can traverse upward from any node. The two-pointer technique with path synchronization ensures both pointers travel equal distances and meet exactly at the LCA, achieving optimal O(1) space complexity!
Asked in
Facebook 45 Microsoft 38 Amazon 32 Google 28
89.3K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen