Untitled

mail@pastecode.io avatar
unknown
python
2 months ago
453 B
0
Indexable
Never
class Solution:    
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        def traverse(curr):
            if not curr: 
                return None

            if curr in [p, q]: 
                return curr

            l = traverse(curr.left)
            r = traverse(curr.right)

            if l and r:
                return curr

            return l or r
        
        return traverse(root)
Leave a Comment