Lowest Common Ancestor of a Binary Tree III — LeetCode 1650 Python Solution
MediumLeetCode PremiumTreeHash TableTwo PointersBinary Tree
- Problem
- #1650
- Pattern
- Two Pointers
- Reading time
- 4 min
- Source
- leetcode.com
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 nodeComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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
LeetCode 236Lowest Common Ancestor of a Binary TreeMediumLeetCode 653Two Sum IV - Input is a BSTEasyLeetCode 105Construct Binary Tree from Preorder and Inorder TraversalMediumLeetCode 106Construct Binary Tree from Inorder and Postorder TraversalMediumLeetCode 508Most Frequent Subtree SumMediumLeetCode 652Find Duplicate SubtreesMedium
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.