Advertisement
smj007

LCA of binary tree

Aug 5th, 2024
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.82 KB | None | 0 0
  1. """
  2. # Definition for a Node.
  3. class Node:
  4.    def __init__(self, val):
  5.        self.val = val
  6.        self.left = None
  7.        self.right = None
  8.        self.parent = None
  9. """
  10.  
  11. class Solution:
  12.     def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
  13.  
  14.         # check whether p is descenet of q -> q
  15.         # check whether q is descent of p -> p
  16.  
  17.         # check whether p descenet of q.parent -> q.parent
  18.         # check wether q descent of p.parent ->
  19.  
  20.  
  21.         def is_descendent(a, b):
  22.             while a:
  23.                 if a == b:
  24.                     return True
  25.                 a = a.parent
  26.             return False
  27.  
  28.         if is_descendent(p, q):
  29.             return q
  30.         if is_descendent(q, p):
  31.             return p
  32.  
  33.         return self.lowestCommonAncestor(p.parent, q.parent)
  34.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement