-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeastCommonAncestor.py
40 lines (37 loc) · 1023 Bytes
/
LeastCommonAncestor.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
33
34
35
36
37
38
39
40
# https://www.interviewbit.com/problems/least-common-ancestor/
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def findPath(root, elem, path):
if not root:
return False
if root.val == elem:
path.insert(0, root.val)
return True
if findPath(root.left, elem, path):
path.insert(0, root.val)
return True
if findPath(root.right, elem, path):
path.insert(0, root.val)
return True
return False
class Solution:
# @param A : root node of tree
# @param B : integer
# @param C : integer
# @return an integer
def lca(self, A, B, C):
path1 = []
findPath(A, B, path1)
path2 = []
findPath(A, C, path2)
result = -1
i = 0
while i < len(path1) and i < len(path2):
if path1[i] == path2[i]:
result = path1[i]
i += 1
return result