• 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
    
    
  • 相关阅读:
    shell面试题整理
    用循环链表实现Josephus问题
    in与exists的区别
    单链表的建立/测长/打印/删除/排序/逆序/寻找中间值
    float在内存中的存放
    crontab定时任务详解
    螺旋队列问题之二
    螺旋队列问题之一
    android网络编程--从网络下载图片,并保存到内存卡
    android Shader类简介_渲染图像示例
  • 原文地址:https://www.cnblogs.com/sandy-t/p/13195518.html
Copyright © 2020-2023  润新知