88. 最近公共祖先

88. 最近公共祖先

中文English

给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。

最近公共祖先是两个节点的公共的祖先节点且具有最大深度。

样例

样例 1:

输入:{1},1,1
输出:1
解释:
 二叉树如下(只有一个节点):
         1
 LCA(1,1) = 1

样例 2:

输入:{4,3,7,#,#,5,6},3,5
输出:4
解释:
 二叉树如下:

      4
     / \
    3   7
       / \
      5   6
			
 LCA(3, 5) = 4

注意事项

假设给出的两个节点都在树中存在

 
输入测试数据 (每行一个参数)如何理解测试数据?

 

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param: root: The root of the binary search tree.
    @param: A: A TreeNode in a Binary.
    @param: B: A TreeNode in a Binary.
    @return: Return the least common ancestor(LCA) of the two nodes.
    """
    def lowestCommonAncestor(self, root, A, B):
        # write your code here
        #如果root为空的话
        if not root: return None 
    
        #如果A为B的父节点,或者是B为A的父节点
        if root == A or root == B:
            return root
            
        #dfs
        left = self.lowestCommonAncestor(root.left, A, B)
        right = self.lowestCommonAncestor(root.right, A, B)
        
        #排除上面两种情况后,不断的往回找,往父节点找
        #遍历完后,判断left,和right是否为None,如果不为,则最小父节点为root
        if left and right: return root
        
        #如果left,right不在同一边,则root是A和B的LCA,否则,如果是同一边,要么LCA是A,要么是B
        if left: return left
        if right: return right
        
        return None 
        

 

posted @ 2020-08-01 21:48  风不再来  阅读(152)  评论(0编辑  收藏  举报