题目链接
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
文章来源地址https://www.toymoban.com/news/detail-685292.html
代码
# 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 is None or root == p or root == q:
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
if left is None and right is not None:
return right
if left is not None and right is None:
return left
else:
return None
文章来源:https://www.toymoban.com/news/detail-685292.html
到了这里,关于LeetCode(力扣)236. 二叉树的最近公共祖先Python的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!