Lowest Common Ancestor(Python版)

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)


你可能感兴趣的:(算法,代码,python,python)