# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root == p or root == q or root == None:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left is not None and right is not None:
return root
elif left is None and right is not None:
return right
elif right is None and left is not None:
return left
else:
return None
236. 二叉树的最近公共祖先
最新推荐文章于 2024-09-21 17:56:48 发布
本文介绍了如何在二叉树结构中,通过Solution类的lowestCommonAncestor方法寻找两个给定节点p和q的最近公共祖先。该方法使用递归策略遍历树的左子树和右子树,直到找到两个节点或者到达叶子节点。
摘要由CSDN通过智能技术生成