1676. Lowest Common Ancestor of a Binary Tree IV (Medium) - TengnanYao/daily_leetcode GitHub Wiki

# 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':
        nodes = set(nodes)
        def dfs(root):
            if root:
                if root in nodes:
                    return root
                l, r = dfs(root.left), dfs(root.right)
                if l and r:
                    return root
                return l or r
        return dfs(root)