236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
Example:

Note: Not sure if the the order can be improved. Is it O(N) already?
def lowestCommonAncestor(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode'):
if not root:
return None
if root == p or root == q:
return root
leftLCA = lowestCommonAncestor(root.left, p, q)
rightLCA = lowestCommonAncestor(root.right, p, q)
if leftLCA and rightLCA:
return root
if leftLCA:
return leftLCA;
return rightLCA
Comments
Post a Comment