python --- LeetCode之 236. Lowest Common Ancestor of a Binary Tree

题目:
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).”
题目理解:
题目就是要找到二叉树中两个节点的最近公共节点。
方法:
递归,用一个辅助函数以此节点为根结点找p和q,如果在左子树找到p(q),右子树找到q(p),则此节点即为所求,如果在左子树(右子树)找到p和q,则左子树(右子树)停止寻找,返回该节点的右节点(左节点),在右子树(左子树)继续寻找,直到p和q分别在左子树和右子树,则此时的节点即为所求。
代码:

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        return self.heaper(root,p,q)
    def heaper(self, node, p, q):
        if node == None or node ==p or node == q:
            return node
        left = self.heaper(node.left,p,q)   # 如果左子树找到目标节点,则返回左节点,否则就是None
        right = self.heaper(node.right,p,q) # 如果右子树找到目标节点,则返回右节点,否则就是None
        if left and right:
            return node
        if left and not right:   # if left is not None and right is None:
            return left
        if not left and right:
            return right
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值