mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-30 12:46:11 -04:00
Create lowest_common_ancestor.py
This commit is contained in:
parent
bfeb0bf97c
commit
da0f3fd5d8
25
trees_and_graphs/lowest_common_ancestor.py
Normal file
25
trees_and_graphs/lowest_common_ancestor.py
Normal 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
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user