传统办法,第30(29/31 pass)个TC会TLE。先写出来吧,找LCA的算法,亚麻的OA考过。不同的是亚麻OA给了root。
class Solution:
def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
root = self.findroot(p)
print(root.val)
res = self.helper(root, p, q)
return res
def findroot(self, node):
while node.parent != None:
node = node.parent
self.findroot(node)
return node
def helper(self, root, p, q):
if not root:return
if root == p or root == q:return root
left = self.helper(root.left, p, q)
right = self.helper(root.right, p, q)
if left and right:return root
if left:return left
if right:return right
接下来,好好使用parent。
class Solution:
def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
self.resp = []
self.findroot(p, self.resp)
while q:
if q not in self.resp:
q = q.parent
else:
return q
def findroot(self, node, res):
while node:
res.append(node)
node = node.parent
return res