class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root is None:
return None
path = []
path_dict = {}
# 记录当前点经历过的路径,重点
def PreOrder(root, path):
path.append(root)
path_dict[root.val] = path
if root.left:
PreOrder(root.left, path[:])
if root.right:
PreOrder(root.right, path[:])
PreOrder(root, path)
p_path = path_dict[p.val]
q_path = path_dict[q.val]
# print(p_path)
# print(q_path)
res = 0
# 根据已知路径,找到最近公共祖先
for parents in zip(p_path, q_path):
p_parent,q_parent = parents
if p_parent.val == q_parent.val:
res = p_parent
return res
力扣-236 二叉树的最近公共祖先
最新推荐文章于 2022-09-29 19:18:51 发布