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
Lowest Common Ancestor (Binary Tree III) INPUT 3 5 p 1 q 6 2 0 8 7 4 p = 5 (red node) q = 1 (orange node) ALGORITHM STEPS 1 Get Path from p to Root 5 --> 3 (path length: 2) 5 --> 3 2 Get Path from q to Root 1 --> 3 (path length: 2) 1 --> 3 3 Store p's Path in Set visited = {5, 3} {5, 3} 4 Traverse q's Path Find first node in set 1 --> 3 OK FINAL RESULT 3 LCA 5 1 6 2 0 8 Output: 3 Node 3 is the lowest common ancestor of 5 and 1 Key Insight: Since each node has a parent pointer, we can traverse from any node to the root. Store p's ancestors in a set, then traverse q's path until we find a node in the set. Time: O(h) where h is tree height | Space: O(h) for storing ancestors TutorialsPoint - Lowest Common Ancestor of a Binary Tree III | Optimal Solution (Two Pointer with Parent Refs)
Asked in
Facebook 45 Microsoft 35 Amazon 30 Google 25
89.3K Views
Medium 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