class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val >q.val:
p,q =q,p
while True:
if root.val>q.val:
root = root.left
elif root.val < p.val:
root = root.right
else:
return root
def create(ceng,tree):
ln = []
for i in range(ceng):
for j,c in enumerate(tree):
if j<pow(2,i)-1 or j>pow(2,i+1)-2:continue
tmp = TreeNode(c)
ln.append(tmp)
if j >0:
if (j-1)/2==int((j-1)/2):ln[int((j-1)/2)].left = tmp
if (j-1)/2>int((j-1)/2):ln[int((j-1)/2)].right = tmp
return ln
ceng = 4#int(input().strip())
tree = [int(i) for i in '9 6 15 2 -1 12 25 -1 -1 -1 -1 -1 -1 20 37'.strip().split()]
son1,son2 = 12,20#[int(i) for i in input().strip().split()]
root = create(ceng,tree)
s = Solution()
p = TreeNode(son1)
q = TreeNode(son2)
print(s.lowestCommonAncestor(root[0],p,q).val)