zoukankan      html  css  js  c++  java
  • LeetCode 236.二叉树的最近公共祖先

    给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

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

    # 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:
                return None
            if root == p:
                return p 
            if root == q:
                return q
            """
            如果root是null,则说明我们已经找到最底了,返回null表示没找到
            如果root与p相等或者与q相等,则返回root
            如果左子树没找到,递归函数返回null,证明p和q同在root的右侧,那么最终的公共祖先就是右子树找到的结点
            如果右子树没找到,递归函数返回null,证明p和q同在root的左侧,那么最终的公共祖先就是左子树找到的结点
    
            """
            L = self.lowestCommonAncestor(root.left,p,q)
            R = self.lowestCommonAncestor(root.right,p,q)
            if L and R:
                return root 
            return L if L else R 
    
    
    
    class Solution:
        def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
            has_p,has_q,ancestor = self.solver(root,p,q)
            return ancestor
    
        def solver(self,root,p,q):
            if root is None:
                return False,False,None 
            has_p_left,has_q_left,ancestor_left = self.solver(root.left,p,q)
            has_p_right,has_q_right,ancestor_right = self.solver(root.right,p,q)
            if has_p_left is True or has_p_right is True or root.val == p.val:
                has_p = True
            else:
                has_p = False
            if has_q_left is True or has_q_right is True or root.val == q.val:
                has_q = True
            else:
                has_q = False
            if ancestor_left is not None:
                ancestor = ancestor_left
            elif ancestor_right is not None:
                ancestor = ancestor_right
            elif ancestor_left is None and ancestor_right is None:
                if has_p is True and has_q is True:
                    ancestor = root 
                else: 
                    ancestor = None
            return has_p,has_q,ancestor
    
    
  • 相关阅读:
    210111做个期望值低的人
    error_1 springboot `com.mysql.jdbc.Driver'问题
    error_2 springboot mysql时区设置
    17_springboot Restful风格
    15_JSON springboot
    13_springboot文件上传
    12_springboot myBatis crud
    11_springboot JPA crud
    Swagger导出MarkDown
    Docker 使用中的一些问题
  • 原文地址:https://www.cnblogs.com/sandy-t/p/13195518.html
Copyright © 2011-2022 走看看