mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-24 09:21:24 -04:00
👾
This commit is contained in:
parent
1d44d182e2
commit
a85ed914d3
320 changed files with 0 additions and 0 deletions
29
trees/lowest_common_ancestor.py
Normal file
29
trees/lowest_common_ancestor.py
Normal file
|
@ -0,0 +1,29 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
'''
|
||||
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
|
||||
'''
|
||||
|
||||
class Tree:
|
||||
def lowest_common_ancestor(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…
Add table
Add a link
Reference in a new issue