Description:
Write a program to determine the lowest common ancestor of two nodes in a binary search tree. You may hardcode the following binary search tree in your program:
30
|
____
| |
8 52
|
____
| |
3 20
|
____
| |
10 29
Input sample:
The first argument will be a text file containing 2 values that represent two nodes within the tree, one per line. e.g.
8 52 3 29
Output sample:
Print to stdout, the least common ancestor, one per line.
e.g.
30 8
解题方案:
import sys
class node:
def __init__(self,value):
self.value = value
self.father = None
def addfather(self,father):
self.father = father
def height(n):
result = 0
while n.father != None:
result += 1
n = n.father
return result
def initTree(tree):
n1 = node(30)
n2 = node(8)
n3 = node(3)
n4 = node(20)
n5 = node(10)
n6 = node(29)
n7 = node(52)
n2.addfather(n1)
n7.addfather(n1)
n3.addfather(n2)
n4.addfather(n2)
n5.addfather(n4)
n6.addfather(n4)
tree['30'] = n1
tree['8'] = n2
tree['3'] = n3
tree['20'] = n4
tree['10'] = n5
tree['29'] = n6
tree['52'] = n7
def lca(a,b):
if a != None and b != None:
if a.father == b.father:
print a.father.value
else:
ha = height(a)
hb = height(b)
if ha == hb:
lca(a.father,b.father)
elif ha > hb:
lca(a.father,b)
else:
lca(a,b.father)
if __name__ == "__main__":
argv = sys.argv
inf = open(argv[1],'r')
tree = {}
initTree(tree)
#print tree
while True:
line = inf.readline()
if len(line) == 0:
break
#print line
ll = line.split()
a = tree.get(ll[0],None)
#print a.value
b = tree.get(ll[1],None)
#print b.value
lca(a,b)
该程序旨在确定给定二叉搜索树中两个节点的最低公共祖先。通过创建节点类、初始化树结构并定义计算最近公共祖先的函数来实现。在main函数中,从输入文件读取节点值,并调用lca函数进行计算并输出结果。
441

被折叠的 条评论
为什么被折叠?



