Lowest Common Ancestor of a Binary Tree III — LeetCode 1650 Python Solution

MediumLeetCode PremiumTreeHash TableTwo PointersBinary Tree
Problem
#1650
Reading time
4 min

The problem

Given two nodes of a binary tree p and q, return their lowest common ancestor (LCA). Each node will have a reference to its parent node.

Example

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node parent;
}

Python solution

Python
"""
# Definition for a Node.
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
        self.parent = None
"""


class Solution:
    def lowestCommonAncestor(self, p: "Node", q: "Node") -> "Node":
        vis = set()
        node = p
        while node:
            vis.add(node)
            node = node.parent
        node = q
        while node not in vis:
            node = node.parent
        return node

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1650. Lowest Common Ancestor of a Binary Tree III is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1650. Lowest Common Ancestor of a Binary Tree III?
LeetCode 1650. Lowest Common Ancestor of a Binary Tree III is rated Medium on LeetCode.
What is the time complexity of LeetCode 1650. Lowest Common Ancestor of a Binary Tree III?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1650. Lowest Common Ancestor of a Binary Tree III?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1650. Lowest Common Ancestor of a Binary Tree III cover?
LeetCode 1650. Lowest Common Ancestor of a Binary Tree III is tagged Tree, Hash Table, Two Pointers and Binary Tree on LeetCode.
Is LeetCode 1650. Lowest Common Ancestor of a Binary Tree III a premium problem?
Yes. LeetCode 1650. Lowest Common Ancestor of a Binary Tree III is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview