# 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:
     #当前节点为空了 直接返回None;当前节点为p 或 q 则找到了它们自身 返回给上一层做判断
if not root or root.val == p.val or root.val == q.val: return root
     #递归左子树和右子树 l
= self.lowestCommonAncestor(root.left, p , q) r = self.lowestCommonAncestor(root.right, p , q)
     ##两边都有 证明p q一定是分别在左右节点上 root一定是公共祖先;只有一边有 root一定不是最近公共祖先 直接把子节点传递回来
return root if l and r else l or r

 

posted on 2020-04-23 23:40  topass123  阅读(150)  评论(0)    收藏  举报