题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
https://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
# def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param root TreeNode类 # @param o1 int整型 # @param o2 int整型 # @return int整型 # class Solution: def __init__(self) -> None: self.paths = [] self.pathhis = [] def findp(self,root,p): if root is None: return False else: self.pathhis.append(root.val) if root.val==p: self.paths.append(self.pathhis) self.pathhis = [] return True else: leftg = self.findp(root.left,p) rightg = self.findp(root.right,p) flag = leftg or rightg if flag is False: self.pathhis.pop() return flag def lowestCommonAncestor(self , root: TreeNode, p: int, q: int) -> int: # write code here getp = self.findp(root,p) getq = self.findp(root,q) i = 0 res = root.val # 比较两个路径,找到第一个不同的点 path1 = self.paths[0] path2 = self.paths[1] while i < len(path1) and i < len(path2): if path1[i] == path2[i]: # 最后一个相同的节点就是最近公共祖先 res = path1[i] i += 1 else: break return res