Leetcode 1816 Solution

This article provides solution to leetcode question 1816 (lowest-common-ancestor-of-a-binary-tree-iv)

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iv

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':
        nodes = set([node.val for node in nodes])

        ans = None
        def dfs(node):
            nonlocal ans

            if ans:
                return 0

            if not node:
                return 0

            cnt = int(node.val in nodes)
            cnt += dfs(node.left)
            cnt += dfs(node.right)

            if ans == None and cnt == len(nodes):
                ans = node
                return 0

            return cnt

        dfs(root)
        return ans