Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- # Definition for a Node.
- class Node:
- def __init__(self, val):
- self.val = val
- self.left = None
- self.right = None
- self.parent = None
- """
- class Solution:
- def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
- # check whether p is descenet of q -> q
- # check whether q is descent of p -> p
- # check whether p descenet of q.parent -> q.parent
- # check wether q descent of p.parent ->
- def is_descendent(a, b):
- while a:
- if a == b:
- return True
- a = a.parent
- return False
- if is_descendent(p, q):
- return q
- if is_descendent(q, p):
- return p
- return self.lowestCommonAncestor(p.parent, q.parent)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement