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

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的最近邻共同祖先。

猜你喜欢

转载自blog.csdn.net/qq_17753903/article/details/82587455