-
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
andq
as the lowest node inT
that has bothp
andq
as descendants (where we allow a node to be a descendant of itself).”
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