LeetCode 236. 二叉树的最近公共祖先(递归)

题目描述

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

思路

详见链接

代码

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):
		if root in {None, p ,q}:
			return root
		left = self.lowestCommonAncestor(root.left,p,q)
		right = self.lowestCommonAncestor(root.right,p,q)
		if left and right:
			return root
		return left or right
发布了80 篇原创文章 · 获赞 239 · 访问量 7075

猜你喜欢

转载自blog.csdn.net/weixin_37763870/article/details/104436302