forked from lupamo3-zz/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Youngest_Common_Ancestor.py
31 lines (23 loc) · 1.07 KB
/
Youngest_Common_Ancestor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# https://www.algoexpert.io/questions/Youngest%20Common%20Ancestor
# O(d) time - where d id the depth | O(1) space
def get_youngest_common_ancestor(top_ancestor, descendant_one, descendant_two):
depth_one = get_descendant_depth(descendant_one, top_ancestor)
depth_two = get_descendant_depth(descendant_two, top_ancestor)
if depth_one > depth_two:
return backtrack_ancestral_tree(descendant_one, descendant_two, depth_one - depth_two)
else:
return backtrack_ancestral_tree(descendant_two, descendant_one, depth_two - depth_one)
def get_descendant_depth(descendant, top_ancestor):
depth = 0
while descendant != top_ancestor:
descendant = descendant.ancestor
depth += 1
return depth
def backtrack_ancestral_tree(lower_descendant, higher_descendant, diff):
while diff > 0:
lower_descendant = lower_descendant.ancestor
diff -= 1
while lower_descendant != higher_descendant:
lower_descendant = lower_descendant.ancestor
higher_descendant = higher_descendant.ancestor
return lower_descendant