-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathlca.py
More file actions
32 lines (25 loc) · 660 Bytes
/
Copy pathlca.py
File metadata and controls
32 lines (25 loc) · 660 Bytes
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
'''
Find the lowest (nearest) common ancestor between two nodes
in a tree.
'''
class Node(object):
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
def find_lca(tree, a, b):
'''
Find the lowest (nearests) common ancestor of a and b.
We assume a and b exist in the tree.
'''
if tree == a:
return a
if tree == b:
return b
a_left = is_child(a, tree.left)
b_left = is_child(b, tree.left)
if a_left and b_left:
return find_lca(tree.left, a, b)
if a_left or b_left:
return tree
return find_lca(tree.right, a, b)