Lowest Common Ancestor of a Binary Tree IV — LeetCode 1676 Python Solution
- Problem
- #1676
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a binary tree and an array of TreeNode objects nodes, return the lowest common ancestor (LCA) of all the nodes in nodes. All the nodes will exist in the tree, and all values of the tree's nodes are unique.
Example
- Input
- root = [3,5,1,6,2,0,8,null,null,7,4], nodes = [4,7]
- Output
- 2
- Explanation
- The lowest common ancestor of nodes 4 and 7 is node 2.
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(
self, root: 'TreeNode', nodes: 'List[TreeNode]'
) -> 'TreeNode':
def dfs(root):
if root is None or root.val in s:
return root
left, right = dfs(root.left), dfs(root.right)
if left and right:
return root
return left or right
s = {node.val for node in nodes}
return dfs(root)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n + m) |
| Space | O(n + m) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV?
- LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV?
- The Python solution on this page runs in O(n + m).
- What is the space complexity of LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV?
- The Python solution on this page uses O(n + m) auxiliary space.
- What topics does LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV cover?
- LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV is tagged Tree, Depth-First Search, Hash Table and Binary Tree on LeetCode.
- Is LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV a premium problem?
- Yes. LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.