问题
Write following functions body. 2 Nodes are passed as parameter. You need to find Least Common Ancestor and print its value. Node structure is as following:
class Node{
value;
parent;
}
Here is the code that I have, but it works with a different Node structure. I am trying to replace .left and .right attributes with .parent. Will replacing these attributes take less memory in the program? How will it affect runtime?
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)
来源:https://stackoverflow.com/questions/59253432/least-common-ancestor-in-python