2023.6.15
关键不在于递归的终止条件,而在于递归的单步逻辑
当到达最近祖先之前,左右孩子向中传递一边传递的是p/q另一边传递的是None,当到达最近祖先时,此节点左孩子传的是p/q,右孩子传的是q/p,此时此节点向上返回的是自己的最近祖先root,再之后节点左右孩子一边返还祖先root一边返还None,此时节点向上返还祖先root
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.p = p
self.q = q
return self.composeporq(root)
def composeporq(self, root):
if root == self.p:
return root
if root == self.q:
return root
if root == None:
return None
ifleft = self.composeporq(root.left)
ifright = self.composeporq(root.right)
if ifleft == None and ifright == None:
return None
elif ifleft != None and ifright == None: # 单边
return ifleft
elif ifright != None and ifleft == None:
return ifright
else: return root