Skip to content

Latest commit

 

History

History
29 lines (22 loc) · 1.26 KB

236.-lowest-common-ancestor-of-a-binary-tree.md

File metadata and controls

29 lines (22 loc) · 1.26 KB

236. Lowest Common Ancestor of a Binary Tree

  • Medium

  • Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

    According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Analysis

We start from the top root and go into the tree and look for where p and q are. If we find them, we return them. That means if I am at a node that the left child returned something while the right child didn't, I know that the LCA would be on the left child. Similar fashion with the right child.

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        if not root: return None
        if p == root or q == root:
            return root
        left = self.lowestCommonAncestor(root.left, p , q)
        right = self.lowestCommonAncestor(root.right, p , q)
        
        if left and right:
            return root
        if not left:
            return right
        if not right:
            return left