236. Lowest Common Ancestor of a Binary Tree

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
return self.rec(root,p,q)

def rec(self,root,p,q):
if root ==None or (root==p) or (root==q):
return root
left =self.rec(root.left,p,q)
right = self.rec(root.right,p,q)

if left ==None:
return right
elif right ==None:
return left
else:
return root

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.