mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update bt_lowest_common_ancestor.py
This commit is contained in:
parent
f41011e849
commit
95fd556031
@ -3,25 +3,27 @@
|
|||||||
# author: bt3gl
|
# author: bt3gl
|
||||||
|
|
||||||
|
|
||||||
class Tree:
|
def lowest_common_ancestor(root, p, q):
|
||||||
|
|
||||||
def lowest_common_ancestor(self, root, p, q):
|
stack = [root]
|
||||||
|
parent = {root: None}
|
||||||
|
|
||||||
def dfs(root, p, q):
|
while p not in parent or q not in parent:
|
||||||
|
|
||||||
if not root:
|
node = stack.pop()
|
||||||
return False
|
if node:
|
||||||
|
parent[node.left] = node
|
||||||
|
parent[node.right] = node
|
||||||
|
stack.append(node.left)
|
||||||
|
stack.append(node.right)
|
||||||
|
|
||||||
left = dfs(root.left, p, q)
|
ancestors = set()
|
||||||
right = dfs(root.right, p, q)
|
while p:
|
||||||
mid = root == p or root == q
|
ancestors.add(p)
|
||||||
|
p = parent[p]
|
||||||
|
|
||||||
if mid + left + right >= 2:
|
while q not in ancestors:
|
||||||
self.answer = root
|
q = parent[q]
|
||||||
|
|
||||||
return left or right or mid
|
return q
|
||||||
|
|
||||||
dfs(root, p, q)
|
|
||||||
|
|
||||||
return self.answer
|
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user