<filename>tree/0236_lowest_common_ancestor_of_a_binary_tree/0236_lowest_common_ancestor_of_a_binary_tree.py

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        if not root:
            return None

        if root == p or root == q:
            return root

        left = None
        right = None
        if root.left:
            left = self.lowestCommonAncestor(root.left, p, q)
        if root.right:
            right = self.lowestCommonAncestor(root.right, p, q)
        
        if left and right:
            return root
        
        if left or right:
            return left if left else right
<filename>tree/0236_lowest_common_ancestor_of_a_binary_tree/0236_lowest_common_ancestor_of_a_binary_tree.py

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        if not root:
            return None

        if root == p or root == q:
            return root

        left = None
        right = None
        if root.left:
            left = self.lowestCommonAncestor(root.left, p, q)
        if root.right:
            right = self.lowestCommonAncestor(root.right, p, q)
        
        if left and right:
            return root
        
        if left or right:
            return left if left else right