mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-08 09:45:28 -04:00
Update and rename lowest_common_ancestor.py to bt_lowest_common_ancestor.py
This commit is contained in:
parent
ca5c15c9b6
commit
7520042ef9
1 changed files with 2 additions and 4 deletions
27
trees/bt_lowest_common_ancestor.py
Normal file
27
trees/bt_lowest_common_ancestor.py
Normal file
|
@ -0,0 +1,27 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
|
||||
class Tree:
|
||||
|
||||
def lowest_common_ancestor(self, root, p, q):
|
||||
|
||||
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…
Add table
Add a link
Reference in a new issue