mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 12:16:14 -04:00
30 lines
574 B
Python
30 lines
574 B
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
# author: bt3gl
|
|
|
|
|
|
def lowest_common_ancestor(root, p, q):
|
|
|
|
stack = [root]
|
|
parent = {root: None}
|
|
|
|
while p not in parent or q not in parent:
|
|
|
|
node = stack.pop()
|
|
if node:
|
|
parent[node.left] = node
|
|
parent[node.right] = node
|
|
stack.append(node.left)
|
|
stack.append(node.right)
|
|
|
|
ancestors = set()
|
|
while p:
|
|
ancestors.add(p)
|
|
p = parent[p]
|
|
|
|
while q not in ancestors:
|
|
q = parent[q]
|
|
|
|
return q
|
|
|