236. 二叉树的最近公共祖先
- 主要思想:定义lowestCommonAncestor(root,p,q)函数,如果p,q都在root这棵树里,则返回它们的最近公共祖先;如果p和q只有一个在root这颗树中,则返回在root这棵树中的p或q;如果p和q都不在root这棵树中,则返回None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root == None or root == p or root == q: return root
left_res = self.lowestCommonAncestor(root.left, p, q)
right_res = self.lowestCommonAncestor(root.right, p, q)
return root if left_res and right_res else left_res if left_res else right_res
P(x1,⋯ ,xn)=∏i=0P(xi∣π(xi))P\left(x_{1}, \cdots, x_{n}\right)=\prod_{i=0} P\left(x_{i} | \pi\left(x_{i}\right)\right)P(x1,⋯,xn)=∏i=0P(xi∣π(xi))