Title description
Given a binary tree, find the nearest common ancestor of the two specified nodes in the tree.
The definition of the most recent public ancestor in Baidu Encyclopedia is: "For the two nodes p and q of the rooted tree T, the most recent public ancestor is represented as a node x, satisfying that x is the ancestor of p and q and the depth of x is as large as possible (A node can also be its own ancestor.)
For example, given the following binary tree: root = [3,5,1,6,2,0,8, null, null, 7,4]
Ideas
Code
class Solution:
def lowestCommonAncestor(self,root,p,q):
if not root or root.val ==p or root.val == q:
return root
left = self.lowestCommonAncestor(root.left,p,q)
right = self.lowestCommonAncestor(root.right,p,q)
if not left:
return right
if not right:
return left
return root