Skip to content

Latest commit

 

History

History
23 lines (22 loc) · 694 Bytes

236. Lowest Common Ancestor of a Binary Tree.md

File metadata and controls

23 lines (22 loc) · 694 Bytes

236. Lowest Common Ancestor of a Binary Tree (Medium)

[tag] Recursion, tree

  • return root if found p or q and pass it up.
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root:
            return None
        if root == p or root == q:
            return root
        left, right = None, None
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)        
        if left and right:
            return root
        elif left:
            return left
        elif right:
            return right
        else:
            return None