Lowest Common Ancestor of a Binary Tree III - Problem
Given two nodes p and q of a binary tree, return their lowest common ancestor (LCA).
Each node will have a reference to its parent node. The definition for Node is below:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)."
Input & Output
Example 1 — Basic Tree Structure
$
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. Node 3 is the lowest node that has both 5 and 1 as descendants.
Example 2 — One Node is Ancestor
$
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, node 5 is their lowest common ancestor.
Example 3 — Same Node
$
Input:
Tree: [1,2], p = 1, q = 1
›
Output:
1
💡 Note:
The LCA of a node with itself is the node itself.
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
Understanding the Visualization
1
Input
Binary tree with parent pointers and two target nodes p and q
2
Process
Use parent pointers to traverse upward from both nodes
3
Output
Return the lowest node that is ancestor of both p and q
Key Takeaway
🎯 Key Insight: Parent pointers transform tree LCA into a linked list intersection problem
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code