leetcode 236Lowest Common Ancestor of a Binary Tree [python]

来源:互联网 发布:四个字的网络用语 编辑:程序博客网 时间:2024/05/21 07:08
  • I.题目简述
  • II.思路及实现
  • III.总结归纳
    I.题目简述
    给定一课二叉树,求两个树的最低公共祖先
    这里写图片描述
    [2,5]的最低公共祖先为5
    [2,8]的最低公共祖先为3
    II.思路及实现
    思路:①递归判断树的左右子树是否为这两个节点公共祖先(自顶向下递归方法)
    ②为实现方法①需写相关某一个结点是否为该节点祖先的方法
    扩展:这里类似对于判断二叉树是否为平衡二叉树的思路类似(需要实现求树的深度方法)
# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def lowestCommonAncestor(self, root, p, q):        """        :type root: TreeNode        :type p: TreeNode        :type q: TreeNode        :rtype: TreeNode        """        if not root or p==root or q==root:            return root        if self.isnode(p,q):            return p        if self.isnode(p,q):            return q        if self.isnode(root.left,p) and self.isnode(root.left,q):            return self.lowestCommonAncestor(root.left,p,q)        if self.isnode(root.right,p) and self.isnode(root.right,q):            return self.lowestCommonAncestor(root.right,p,q)        else:            return root    def isnode(self,mother,child):        if mother:            if mother==child:                return True            else:                return self.isnode(mother.left,child) or self.isnode(mother.right,child)        return False        

III.总结归纳
①关于树这类的题目在遍历的方法实现以及树的基本概念的结合是解决此类的问题的基础,大家需要熟悉②让我们一同努力,明天会更好!

0 0
原创粉丝点击