Lowest Common Ancestor of a Binary Tree (Leetcode 236)
Problem Link: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if(root==p or root==q):
return root
if(root is None):
return None
l=self.lowestCommonAncestor(root.left,p,q)
r=self.lowestCommonAncestor(root.right,p,q)
# In this case, root will be LCA
if(l is not None and r is not None):
return root
# In these cases, either p will be below
# q or q will be below p. Hence, return
# the node which is not None
if(l is not None and r is None):
return l
elif(l is None and r is not None):
return r
Last updated