MediumNo. 1650LeetCode Premium
Lowest Common Ancestor of a Binary Tree III — LeetCode 1650 Python Solution
- Pattern
- Two Pointers
- Topics
- Tree, Hash Table, Two Pointers, Binary Tree
- 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
"""
# 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
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0236 | Lowest Common Ancestor of a Binary Tree | Medium |
| 0653 | Two Sum IV - Input is a BST | Easy |
| 0105 | Construct Binary Tree from Preorder and Inorder Traversal | Medium |
| 0106 | Construct Binary Tree from Inorder and Postorder Traversal | Medium |
| 0508 | Most Frequent Subtree Sum | Medium |
| 0652 | Find Duplicate Subtrees | Medium |
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.