Python: самый низкий общий предок в двоичном дереве, вызов на CodeEval
Прежде всего, я знаю, что есть много других тем, посвященных этой проблеме. То, что я хочу знать, - это то, почему мое решение, кажется, не оценивается на 100%, когда я отправляю его на CodeEval. Это только занимает 70%. Когда я тестирую его в своей локальной среде, он отлично работает для всех тестовых ситуаций, которые я в него бросил.
Я знаю, что мое решение не самое эффективное. Я пытался найти собственное решение, которое я бы понял. Я со временем буду сравнивать это с другими. Но перед этим, кто-то может объяснить, пожалуйста, что я здесь делаю не так?
class binary_tree(object):
def __init__(self, value=None, left=None, right=None):
self.value=value
self.left=left
self.right=right
def insert(self, num):
#print "...now:", num
if self.value==num:
return
else:
#print "descending from", self.value
if num<self.value:
if self.left:
#print "descending to left"
self.left.insert(num)
else:
#print "! found empty left"
self.left=binary_tree(num)
else:
if self.right:
#print "descending to right"
self.right.insert(num)
else:
#print "! found empty right"
self.right=binary_tree(num)
def tree_from_list(self, value, numbers):
self.value=value
for num in numbers:
self.insert(num)
def __repr__(self,depth=0):
rtn=""
rtn+="\t"*depth+" "+str(self.value)+"\n"
depth+=1
if self.left:
rtn+="\t"*depth+" left: "
rtn+=self.left.__repr__(depth)
if self.right:
rtn+="\t"*depth+" right: "
rtn+=self.right.__repr__(depth)
return rtn
def find_parent_depth(self, num, depth=0):
if self.left and self.left.value==num:
#returns a list of two values, the first one being
#the depth of the parent, and the second the value
#itself. depth starts at 0, and increases as we descend
return [depth, self.value]
elif self.right and self.right.value==num:
return [depth, self.value]
else:
depth+=1
#checks for which path to descend on
if num<self.value:
if self.left:
return self.left.find_parent_depth(num, depth)
else:
return self.value
else:
if self.right:
return self.right.find_parent_depth(num, depth)
else:
return self.value
#lca = lowest common ancestor
def lca(self, v1, v2):
parent1=self.find_parent_depth(v1)
parent2=self.find_parent_depth(v2)
#checks for which parent has lower depth
if parent1[0]<parent2[0]:
#searches for ancestors till it reaches the same depth level
while parent1[0]!=parent2[0]:
parent2=self.find_parent_depth(parent2[1])
#checks if the ancestors coincide at that depth
if parent1[1]==parent2[1]:
#if they do, returns the parent value
#THIS IS IT
return parent1[1]
#if it doesn't, we need to raise the level of the lowest one
#and do it all over again
else:
return self.lca(parent1[1], parent2[1])
else:
#searches for ancestors till it reaches the same depth level
while parent2[0]!=parent1[0]:
parent1=self.find_parent_depth(parent1[1])
#checks if the ancestors coincide at that depth
if parent1[1]==parent2[1]:
#if they do, returns the parent value
#THIS IS IT
return parent1[1]
#if it doesn't, we need to raise the level of the lowest one
#and do it all over again
else:
return self.lca(parent2[1], parent1[1])
dis=binary_tree()
dis.tree_from_list(30, [8, 52, 3, 20, 10, 29, 12, 90, 89, 1])
print dis.lca(89, 12)
1 ответ
У меня была похожая проблема. Дано:
30
_|___
| |
8 52
_|___
| |
3 20
_|___
| |
10 29
Мое зависание было связано с определением LCA.
Я обнаружил, что самый низкий общий предок 20 и 29 - это 20, а не 8, как я первоначально думал, учитывая примеры в указаниях. Другой пример - LCA 8 и 20 - 8.
После корректировки кода моя подача прошла 100%.
Надеюсь это поможет. Ура!