LeetCode-236. Lowest Common Ancestor of a Binary Tree-python3代码+解题思路

14 篇文章 0 订阅
9 篇文章 0 订阅

0.原题:

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree:  root = [3,5,1,6,2,0,8,null,null,7,4]

 

翻译:

给定一棵二叉树,在树中找到两个给定节点的最近邻的共同祖先(LCA)。

根据Wikipedia上LCA的定义:“最近邻的共同祖先,是在两个节点p和q之间的最近邻的节点,即p和q都是后代(我们允许一个节点成为其自身的后代)。

 

1.代码:

# 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, 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 = None
        right = None
        
        left = self.lowestCommonAncestor(root.left,p,q)
        right = self.lowestCommonAncestor(root.right,p,q)
        
        if (left != None) and (right != None):
            return root
        else:
            return (left if(left != None) else(right))

 

2.思路:

整体思路:采用递归,逐层查找。

step1:设置递归结束条件

如果,查找的子树为空时,即root == 0,需要结束递归,并返回None;

如果,p为当前树的子节点,即root == p,那么p、q的最近邻共同祖先就是p本身,返回p;

如果,q为当前树的子节点,即root == q,那么p、q的最近邻共同祖先就是q本身,返回q;

综上所述:递归结束条件为:root == None or root == p or root == q,返回值都等于 root

step2:查找子树

如果递归没有结束,就说明p和q都在子树之中,需要对子树进行查找。

设置left、right用于存放返回值。

left存放左子树的查找结果,right存放右子树查找结果。

如果,如果在左右子树中,分别查找到了p或者q,那么这时候的root节点就是p、q的最近邻共同祖先。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值