Lowest Common Ancestor of a Binary Tree – Python 3 (Week 14 – 14)

 """
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param: root: The root of the binary search tree.
    @param: A: A TreeNode in a Binary.
    @param: B: A TreeNode in a Binary.
    @return: Return the least common ancestor(LCA) of the two nodes.
    """
    def lowestCommonAncestor(self, root, A, B):
        # write your code here
        
        if not root:
            return None
        
        if root is A or root is B:
            return root
            
        left = self.lowestCommonAncestor(root.left, A, B)
        right = self.lowestCommonAncestor(root.right, A, B)
        
        if left is None and right is None:
            return None
        if right is None:
            return left
        if left is None:
            return right
        
        return root

Time, Space O(n).

Leave a comment

Design a site like this with WordPress.com
Get started