1644. Lowest Common Ancestor of a Binary Tree II

Updated: 2024-03-12
1 min read

On This Page

LeetCode problem 1644

# 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':
        def dfs(root, p, q):
            if root is None:
                return False
            l = dfs(root.left, p, q)
            r = dfs(root.right, p, q)
            nonlocal res
            if l and r:
                res = root
            if (l or r) and (root.val == p.val or root.val == q.val):
                res = root
            return l or r or root.val == p.val or root.val == q.val

        res = None
        dfs(root, p, q)
        return res