美文网首页
Lint 88. Lowest Common Ancestor

Lint 88. Lowest Common Ancestor

作者: Mree111 | 来源:发表于2019-10-16 02:40 被阅读0次

    Description

    Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.

    Solution

    """
    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
           if root is None:
               return None
           if root is A or root is B:
               return root
           left = self.lowestCommonAncestor(root.left,A,B)
           right = self.lowestCommonAncestor(root.right,A,B)
           if left is not None and right is not None:
               return root
           
           if left is not None:
               return left 
           if right is not None:
               return right
               
           return None
    

    相关文章

      网友评论

          本文标题:Lint 88. Lowest Common Ancestor

          本文链接:https://www.haomeiwen.com/subject/vntsmctx.html