-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLCA.py
32 lines (28 loc) · 819 Bytes
/
LCA.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
30
31
32
# Finding the Lowest Common Ancestor (LCA) for a binary tree.
class node:
def __init__(self,val):
self.key = val
self.left = None
self.right = None
def findPath(root,path,k):
if root is None:
return False
path.append(root.key)
if root.key == k:
return True
if ((root.left != None and findPath(root.left, path, k)) or
(root.right!= None and findPath(root.right, path, k))):
return True
path.pop()
return False
def lca(root,n1,n2):
path1 = []
path2 = []
if (not findPath(root, path1, n1) or not findPath(root, path2, n2)):
return -1
i = 0
while(i < len(path1) and i < len(path2)):
if path1[i] != path2[i]:
break
i += 1
return path1[i-1]