Create lowest_common_ancestor.py

This commit is contained in:
bt3gl 2023-07-29 17:41:24 -07:00 committed by GitHub
parent bfeb0bf97c
commit da0f3fd5d8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,25 @@
'''
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