mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-30 04:36:08 -04:00
26 lines
654 B
Python
26 lines
654 B
Python
'''
|
|
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
|
|
'''
|
|
|
|
class ThisTree:
|
|
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
|
|
|
|
def dfs(root, p, q):
|
|
|
|
if not root:
|
|
return False
|
|
|
|
left = dfs(root.left, p, q)
|
|
right = dfs(root.right, p, q)
|
|
mid = root == p or root == q
|
|
|
|
if mid + left + right >= 2:
|
|
self.answer = root
|
|
|
|
return left or right or mid
|
|
|
|
dfs(root, p, q)
|
|
|
|
return self.answer
|
|
|