Leetcode 1780 Solution

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

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

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', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        nodes = {p.val, q.val}

        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