0
点赞
收藏
分享

微信扫一扫

首个共同祖先(非二叉搜索树)

小云晓云 2022-04-18 阅读 4
python

思路:

若根节点为空或者根节点等于p或者q,则最近公共祖先就是root;

分开递归查找,left记录左子树查找的情况;right记录右子树查找的情况。

  1. 若left不为空,right为空,说明p、q都在左子树中,返回left;
  2. 若left为空,right不为空,说明p、q都在右子树中,返回right;
  3. 若left、right都不为空,说明p、q分布在左右子树中,返回root。
# 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:
        #若根节点为空或者根节点等于p和q,则返回root:
        if not root or root==p or root==q:
            return root
        else: 
            left=self.lowestCommonAncestor(root.left,p,q)
            right=self.lowestCommonAncestor(root.right,p,q)
        if  left and right:
            return root
        else:
            return left if left else right 
举报

相关推荐

0 条评论