最近公共祖先 python_最近公共祖先

#Python 版

把其祖先保存下来,然后比较

# -*- coding:utf-8 -*-

class LCA:

def getLCA(self, a, b):

# write code here

if a == b:

return a

ap = [a]

while a !=1:

ap.append(a/2)

a/=2

bp = [b]

while b!=1:

bp.append(b/2)

b/=2

lensa= len(ap)-1

lensb = len(bp)-1

while lensa>=0 and lensb>=0:

if ap[lensa] == bp[lensb]:

lensa-=1

lensb-=1

else:

return ap[lensa+1]

if lensa==-1:

return ap[0]

if lensb ==-1:

return bp[0]

print LCA().getLCA(2,4)

#参考 面试金典 更简单的方式

# -*- coding:utf-8 -*-

class LCA:

def getLCA(self, a, b):

# write code here

while a!=b:

if a>b:

a/=2

elif a

b/=2

else:

break

return a

print LCA().getLCA(2,4)

你可能感兴趣的:(最近公共祖先,python)