两步走,先获取从根节点到两个目标节点的路径,再找公共祖先。
# class TreeNode:
# 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):
self.found=False
#先获取从根节点到两个目标节点的路径,用深度优先搜索来找
def dfsGetPath(self, root: TreeNode, target:int, path=[])->List[int]:
#递归的结束条件
if not root :#root为空
return path
path.append(root.val)
if target==root.val:
self.found = True
return path
else:
#递归调用
self.dfsGetPath(root.left,target,path)
self.dfsGetPath(root.right,target,path)
if self.found == True: #不能省去判断,用来防止节点已经找到,但是被去除
return path
else:
path.pop()#不在这条路径,去除节点做回溯
def lowestCommonAncestor(self , root: TreeNode, o1: int, o2: int) -> int:
path1=self.dfsGetPath(root,o1,path=[])
self.found = False# 重置found
path2=self.dfsGetPath(root,o2,path=[])
minpathDepth=min(len(path1),len(path2))
for i in range(minpathDepth):
if path1[i]==path2[i]:
res=path1[i]
return res
京公网安备 11010502036488号