python中最不常见的祖先

时间:2019-12-09 17:01:12

标签: python memory tree runtime ancestor

编写以下函数主体。 2个节点作为参数传递。您需要找到最不常见的 祖先并打印其值。节点结构如下:

class Node{
value;
parent;
}

这是我所拥有的代码,但它可用于其他Node结构。我试图用.parent替换.left和.right属性。替换这些属性会占用程序更少的内存吗?它将如何影响运行时间?

class Node: 
    def __init__(self, key): 
        self.key =  key 
        self.left = None
        self.right = None

def findPath( root, path, k): 

    if root is None: 
        return False

    path.append(root.key) 

    if root.key == k : 
        return True

    if ((root.left != None and findPath(root.left, path, k)) or
            (root.right!= None and findPath(root.right, path, k))): 
        return True 

    path.pop() 
    return False

def findLCA(root, n1, n2): 

    path1 = [] 
    path2 = [] 

    if (not findPath(root, path1, n1) or not findPath(root, path2, n2)): 
        return -1 

    i = 0 
    while(i < len(path1) and i < len(path2)): 
        if path1[i] != path2[i]: 
            break
        i += 1
    print(path1[i-1])
    return path1[i-1] 


root = Node(1) 
root.left = Node(2) 
root.right = Node(3) 
root.left.left = Node(4) 
root.left.right = Node(5) 
root.right.left = Node(6) 
root.right.right = Node(7) 

findLCA(root, 4, 5)
findLCA(root, 4, 6)
findLCA(root, 3, 4)
findLCA(root, 2, 4)
findLCA(root, 1, 7)
findLCA(root, 3, 7)

0 个答案:

没有答案
相关问题